"""Agent Skills Management API

Provides endpoints for managing agent skills.
"""
import logging
import os
from fastapi import APIRouter
from pydantic import BaseModel
from typing import List, Optional

from src.services.agent_engine import AgentScopeService
from src.services.agent_engine.toolkit import ToolkitFactory
from src.models.schemas import ResponseModel
from src.utils.errors import ErrorCode, AppException

router = APIRouter(tags=["skills"])
logger = logging.getLogger(__name__)


class SkillInfo(BaseModel):
    """Skill information model"""
    name: str
    description: str
    path: str


class RegisterSkillRequest(BaseModel):
    """Request model for registering a skill"""
    skill_dir: str


class SkillPromptResponse(BaseModel):
    """Response model for skill prompt"""
    prompt: Optional[str]
    skills_count: int


@router.get("/skills", response_model=ResponseModel)
async def list_skills():
    """List all available agent skills.

    Returns:
        List of skill information
    """
    skills = []

    try:
        # 使用新的 ToolkitFactory
        all_skills = ToolkitFactory.list_skills()

        for skill_path in all_skills:
            # skill_path 格式: "domain/skill_name"
            domain, skill_name = skill_path.split('/')

            # 读取 SKILL.md 获取描述
            from pathlib import Path
            # Fix path: services/agent_engine/skills (was services/agents/skills)
            skill_dir = Path(__file__).parent.parent / "services" / "agent_engine" / "skills" / domain / skill_name
            skill_md = skill_dir / "SKILL.md"

            description = "No description available"
            if skill_md.exists():
                try:
                    with open(skill_md, 'r', encoding='utf-8') as f:
                        content = f.read()

                    # Extract description from YAML front matter
                    if content.startswith('---'):
                        parts = content.split('---', 2)
                        if len(parts) >= 3:
                            import yaml
                            try:
                                metadata = yaml.safe_load(parts[1])
                                description = metadata.get('description', description)
                            except yaml.YAMLError:
                                pass

                    skills.append(SkillInfo(
                        name=skill_path,  # 使用完整路径作为名称
                        description=description,
                        path=str(skill_dir)
                    ))
                except Exception as e:
                    logger.error(f"Failed to read skill {skill_path}: {e}")

    except Exception as e:
        logger.error(f"Failed to list skills: {e}")

    return ResponseModel(data=skills)


@router.post("/skills/register", response_model=ResponseModel)
async def register_skill(request: RegisterSkillRequest):
    """Register a new agent skill.
    
    Args:
        request: Skill registration request
        
    Returns:
        Success message
        
    Raises:
        HTTPException: If skill registration fails
    """
    try:
        # Validate skill directory
        if not os.path.exists(request.skill_dir):
            raise AppException(
                message=f"Skill directory not found: {request.skill_dir}",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        skill_md = os.path.join(request.skill_dir, "SKILL.md")
        if not os.path.exists(skill_md):
            raise AppException(
                message="SKILL.md file not found in skill directory",
                code=ErrorCode.INVALID_PARAMETER,
                status_code=400
            )
        
        # Register skill (this would need to be implemented in AgentScopeService)
        logger.info(f"Registered skill from: {request.skill_dir}")

        return ResponseModel(data={"message": "Skill registered successfully", "path": request.skill_dir})
        
    except AppException:
        raise
    except Exception as e:
        logger.error(f"Failed to register skill: {e}")
        raise AppException(
                message=str(e),
                code=ErrorCode.INTERNAL_ERROR,
                status_code=500
            )


@router.get("/skills/prompt", response_model=ResponseModel)
async def get_skills_prompt():
    """Get the combined prompt for all registered skills.

    This prompt can be attached to the agent's system prompt.

    Returns:
        Combined skills prompt
    """
    try:
        # 使用 ToolkitFactory
        all_skills = ToolkitFactory.list_skills()
        skills_count = len(all_skills)

        # 获取 skills prompt
        if skills_count > 0:
            toolkit = ToolkitFactory.get_toolkit()
            prompt = toolkit.get_agent_skill_prompt()
        else:
            prompt = None

        return ResponseModel(data={"prompt": prompt, "skills_count": skills_count})

    except Exception as e:
        logger.error(f"Failed to get skills prompt: {e}")
        raise AppException(
                message=str(e),
                code=ErrorCode.INTERNAL_ERROR,
                status_code=500
            )


@router.delete("/skills/{skill_name}", response_model=ResponseModel)
async def remove_skill(skill_name: str):
    """Remove a registered agent skill.
    
    Args:
        skill_name: Name of the skill to remove
        
    Returns:
        Success message
        
    Raises:
        HTTPException: If skill removal fails
    """
    try:
        # This would need to be implemented in AgentScopeService
        logger.info(f"Removed skill: {skill_name}")
        
        return ResponseModel(data={"message": f"Skill '{skill_name}' removed successfully"})
        
    except Exception as e:
        logger.error(f"Failed to remove skill: {e}")
        raise AppException(
                message=str(e),
                code=ErrorCode.INTERNAL_ERROR,
                status_code=500
            )
