"""
api.v1.skills — 能力插件（prompt skill）注册中心 API
（docs/MCP_SKILL_DESIGN.md §2.3，P2）。

GET    /api/v1/skills            列表
POST   /api/v1/skills            新建/更新（loopback-only — 本机配置操作）
PUT    /api/v1/skills/{name}     修改 / 启停
DELETE /api/v1/skills/{name}     删除
POST   /api/v1/skills/permission-diff  预览挂载某组 skill 的工具权限 diff
"""
from __future__ import annotations

from typing import List

from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, Field

from agentpaas.api.deps import get_tenant
from agentpaas.api.middleware.auth import TenantContext
from agentpaas.engine import skill_registry as reg

router = APIRouter(prefix="/skills", tags=["skills"])


def _loopback_only(request: Request) -> None:
    host = (request.client.host if request.client else "") or ""
    if host not in ("127.0.0.1", "::1", "localhost", "testclient"):
        raise HTTPException(status_code=404, detail="Not Found")


class SkillRequires(BaseModel):
    tools: List[str] = Field(default_factory=list)
    mcp_scopes: List[str] = Field(default_factory=list)


class SkillSpec(BaseModel):
    name: str = Field(..., min_length=1)
    version: str = "0.1.0"
    description: str = ""
    prompt: str = ""
    requires: SkillRequires = Field(default_factory=SkillRequires)
    examples: List[str] = Field(default_factory=list)
    enabled: bool = True


class UpdateSkill(BaseModel):
    version: str | None = None
    description: str | None = None
    prompt: str | None = None
    requires: SkillRequires | None = None
    examples: List[str] | None = None
    enabled: bool | None = None


class PermDiffReq(BaseModel):
    config: dict = Field(default_factory=dict)
    skills: List[str] = Field(default_factory=list)


@router.get("")
async def list_skills(_tenant: TenantContext = Depends(get_tenant)):
    return {"skills": reg.list_skills()}


@router.post("", status_code=201)
async def add_skill(spec: SkillSpec, request: Request,
                    _tenant: TenantContext = Depends(get_tenant)):
    _loopback_only(request)
    try:
        saved = reg.upsert_skill(spec.model_dump())
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    return {"ok": True, "skill": saved}


@router.put("/{name}")
async def update_skill(name: str, body: UpdateSkill, request: Request,
                       _tenant: TenantContext = Depends(get_tenant)):
    _loopback_only(request)
    cur = reg.get_skill(name)
    if not cur:
        raise HTTPException(status_code=404, detail="skill not found")
    merged = {**cur, "name": name}
    for k, v in body.model_dump(exclude_none=True).items():
        merged[k] = v
    try:
        saved = reg.upsert_skill(merged)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    return {"ok": True, "skill": saved}


@router.delete("/{name}")
async def delete_skill(name: str, request: Request,
                       _tenant: TenantContext = Depends(get_tenant)):
    _loopback_only(request)
    if not reg.remove_skill(name):
        raise HTTPException(status_code=404, detail="skill not found")
    return {"ok": True}


@router.post("/permission-diff")
async def permission_diff(body: PermDiffReq,
                          _tenant: TenantContext = Depends(get_tenant)):
    """预览：挂载这组 skill 会给 agent 新增哪些工具（含高风险标注）。"""
    return reg.permission_diff(body.config, body.skills)
