"""Skill Management API routes"""

from __future__ import annotations

import logging
from typing import Any

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

logger = logging.getLogger(__name__)

router = APIRouter(tags=["skill-management"])


# ---------------------------------------------------------------------------
# Request / Response models
# ---------------------------------------------------------------------------


class SkillInfo(BaseModel):
    name: str
    version: str
    description: str
    capabilities: list[str]
    dependencies: list[str]
    status: str


class SkillDetail(BaseModel):
    name: str
    version: str
    description: str
    capabilities: list[str]
    dependencies: list[str]
    config: dict[str, Any]
    health_status: str


class CapabilityInfo(BaseModel):
    name: str
    display_name: str
    skill_count: int


# ---------------------------------------------------------------------------
# Helper: extract skill info from Skill object
# ---------------------------------------------------------------------------


def _skill_to_info(skill: Any) -> dict[str, Any]:
    """Convert a Skill object to a dict suitable for API responses."""
    capabilities = []
    if hasattr(skill, "config") and hasattr(skill.config, "capabilities"):
        caps = skill.config.capabilities
        if isinstance(caps, list):
            capabilities = [
                c.tag if hasattr(c, "tag") else str(c) for c in caps
            ]
        elif isinstance(caps, dict):
            capabilities = list(caps.keys())

    dependencies = []
    if hasattr(skill, "config") and hasattr(skill.config, "dependencies"):
        deps = skill.config.dependencies
        if isinstance(deps, list):
            dependencies = deps
        elif isinstance(deps, dict):
            dependencies = list(deps.keys())

    version = ""
    if hasattr(skill, "config") and hasattr(skill.config, "version"):
        version = skill.config.version or ""

    description = ""
    if hasattr(skill, "config") and hasattr(skill.config, "description"):
        description = skill.config.description or ""

    return {
        "name": skill.name,
        "version": version,
        "description": description,
        "capabilities": capabilities,
        "dependencies": dependencies,
        "status": "active",
    }


def _skill_to_detail(skill: Any) -> dict[str, Any]:
    """Convert a Skill object to a detailed dict for API responses."""
    info = _skill_to_info(skill)

    config = {}
    if hasattr(skill, "config"):
        try:
            config = skill.config.to_dict() if hasattr(skill.config, "to_dict") else {}
        except Exception:
            config = {}

    return {
        **info,
        "config": config,
        "health_status": "healthy",
    }


# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------


@router.get("/skill-management/skills")
async def list_skills(
    req: Request,
    capability: str | None = None,
    page: int = 1,
    size: int = 20,
):
    """List all registered skills with optional filtering."""
    skill_registry = req.app.state.skill_registry
    all_skills = skill_registry.list_skills()

    # Apply capability filter
    if capability:
        filtered = []
        for skill in all_skills:
            caps = _skill_to_info(skill)["capabilities"]
            if capability in caps:
                filtered.append(skill)
        all_skills = filtered

    # Pagination
    total = len(all_skills)
    start = (page - 1) * size
    end = start + size
    page_skills = all_skills[start:end]

    return {
        "skills": [_skill_to_info(s) for s in page_skills],
        "total": total,
        "page": page,
        "size": size,
    }


@router.get("/skill-management/skills/{skill_name}")
async def get_skill_detail(skill_name: str, req: Request):
    """Get detailed information about a specific skill."""
    skill_registry = req.app.state.skill_registry
    try:
        skill = skill_registry.get(skill_name)
    except Exception:
        raise HTTPException(status_code=404, detail=f"Skill '{skill_name}' not found")

    return _skill_to_detail(skill)


@router.get("/skill-management/skills/{skill_name}/health")
async def check_skill_health(skill_name: str, req: Request):
    """Check the health of a specific skill."""
    skill_registry = req.app.state.skill_registry
    try:
        skill = skill_registry.get(skill_name)
    except Exception:
        raise HTTPException(status_code=404, detail=f"Skill '{skill_name}' not found")

    # Basic health check - skill exists and is registered
    return {
        "skill_name": skill_name,
        "status": "healthy",
        "message": "技能已注册且可用",
    }


@router.get("/skill-management/capabilities")
async def list_capabilities(req: Request):
    """List all capability tags with skill counts."""
    skill_registry = req.app.state.skill_registry
    all_skills = skill_registry.list_skills()

    # Build capability -> skill count mapping
    cap_counts: dict[str, int] = {}
    for skill in all_skills:
        caps = _skill_to_info(skill)["capabilities"]
        for cap in caps:
            cap_counts[cap] = cap_counts.get(cap, 0) + 1

    # Display name mapping
    display_names: dict[str, str] = {
        "chat": "智能对话",
        "workflow": "工作流编排",
        "knowledge": "知识库",
        "skills": "技能管理",
        "terminal": "智能终端",
        "computer_use": "Computer Use",
        "evolution": "自进化",
        "code": "代码生成",
        "search": "搜索",
        "analysis": "分析",
    }

    capabilities = [
        {
            "name": name,
            "display_name": display_names.get(name, name),
            "skill_count": count,
        }
        for name, count in sorted(cap_counts.items())
    ]

    return {"capabilities": capabilities}


@router.post("/skill-management/skills/{skill_name}/reload")
async def reload_skill(skill_name: str, req: Request):
    """Reload a skill configuration."""
    skill_registry = req.app.state.skill_registry
    try:
        skill = skill_registry.get(skill_name)
    except Exception:
        raise HTTPException(status_code=404, detail=f"Skill '{skill_name}' not found")

    # In a full implementation, this would reload the skill from its config source
    # For now, just return success
    return {
        "skill_name": skill_name,
        "status": "reloaded",
        "message": f"技能 '{skill_name}' 已重新加载",
    }
