"""
Skills route: GET /api/skills, POST /api/skills/config, GET /api/skills/marketplace

技能列表与配置管理。
"""

from __future__ import annotations

import logging

import httpx
from fastapi import APIRouter, Request

logger = logging.getLogger(__name__)

router = APIRouter()

SKILLS_SH_API = "https://skills.sh/api/search"


@router.get("/api/skills")
async def list_skills(request: Request):
    """List all available skills with their config schemas."""
    from openakita.core.agent import Agent

    agent = getattr(request.app.state, "agent", None)
    actual_agent = agent
    if not isinstance(agent, Agent):
        actual_agent = getattr(agent, "_local_agent", None)

    if actual_agent is None:
        return {"skills": []}

    registry = getattr(actual_agent, "skill_registry", None)
    if registry is None:
        return {"skills": []}

    skills = []
    for skill in registry.list_all():
        # config 存储在 ParsedSkill.metadata 中
        config = None
        parsed = getattr(skill, "_parsed_skill", None)
        if parsed and hasattr(parsed, "metadata"):
            config = getattr(parsed.metadata, "config", None) or None

        skills.append({
            "name": skill.name,
            "description": skill.description,
            "system": skill.system,
            "enabled": True,  # 在 registry 中的技能都是已启用的
            "category": skill.category,
            "tool_name": skill.tool_name,
            "config": config,
        })

    return {"skills": skills}


@router.post("/api/skills/config")
async def update_skill_config(request: Request):
    """Update skill configuration."""
    body = await request.json()
    skill_name = body.get("skill_name", "")
    config = body.get("config", {})

    # TODO: Apply config to the skill and persist to .env
    return {"status": "ok", "skill": skill_name, "config": config}


@router.post("/api/skills/install")
async def install_skill(request: Request):
    """安装技能（远程模式替代 Tauri openakita_install_skill 命令）。

    POST body: { "url": "github:user/repo/skill" }
    """
    import asyncio

    body = await request.json()
    url = body.get("url", "").strip()
    if not url:
        return {"error": "url is required"}

    try:
        from openakita.config import settings

        workspace_dir = str(settings.project_root)
    except Exception:
        workspace_dir = str(__import__("pathlib").Path.cwd())

    try:
        from openakita.setup_center.bridge import install_skill as _install_skill

        # install_skill 是同步函数（可能执行 git clone），放到线程中避免阻塞事件循环
        await asyncio.to_thread(_install_skill, workspace_dir, url)
        return {"status": "ok", "url": url}
    except Exception as e:
        logger.error(f"Skill install failed: {e}")
        return {"error": str(e)}


@router.get("/api/skills/marketplace")
async def search_marketplace(q: str = "agent"):
    """Proxy to skills.sh search API (bypasses CORS for desktop app)."""
    from openakita.llm.providers.proxy_utils import (
        get_httpx_transport,
        get_proxy_config,
    )

    try:
        client_kwargs: dict = {"timeout": 15, "follow_redirects": True}

        # 复用项目的代理和 IPv4 设置
        proxy = get_proxy_config()
        if proxy:
            client_kwargs["proxy"] = proxy

        transport = get_httpx_transport()
        if transport:
            client_kwargs["transport"] = transport

        async with httpx.AsyncClient(**client_kwargs) as client:
            resp = await client.get(SKILLS_SH_API, params={"q": q})
            resp.raise_for_status()
            return resp.json()
    except Exception as e:
        logger.warning("skills.sh API error: %s", e)
        return {"skills": [], "count": 0, "error": str(e)}
