"""Skills API routes."""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional

from ieum.skills.load import list_skills, get_skill_content, extract_skill_instructions
from ieum.config import settings

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


class SkillResponse(BaseModel):
    """Skill metadata response."""

    name: str
    description: str
    path: str
    source: str


class SkillDetailResponse(BaseModel):
    """Skill detail response."""

    name: str
    description: str
    path: str
    source: str
    content: str
    instructions: str


class SkillInvokeRequest(BaseModel):
    """Skill invocation request."""

    name: str
    task: Optional[str] = ""


class SkillInvokeResponse(BaseModel):
    """Skill invocation response (returns prompt for agent)."""

    prompt: str
    skill_name: str


@router.get("", response_model=list[SkillResponse])
async def list_available_skills():
    """List all available skills."""
    user_skills_dir = settings.get_user_skills_dir("agent")
    project_skills_dir = settings.get_project_skills_dir()

    skills = list_skills(
        user_skills_dir=user_skills_dir,
        project_skills_dir=project_skills_dir
    )

    return [
        SkillResponse(
            name=s["name"],
            description=s["description"],
            path=s["path"],
            source=s["source"]
        )
        for s in skills
    ]


@router.get("/{skill_name}", response_model=SkillDetailResponse)
async def get_skill_detail(skill_name: str):
    """Get detailed information about a skill."""
    user_skills_dir = settings.get_user_skills_dir("agent")
    project_skills_dir = settings.get_project_skills_dir()

    skills = list_skills(
        user_skills_dir=user_skills_dir,
        project_skills_dir=project_skills_dir
    )

    skill = next((s for s in skills if s["name"] == skill_name), None)
    if not skill:
        raise HTTPException(status_code=404, detail=f"Skill '{skill_name}' not found")

    content = get_skill_content(skill["path"])
    instructions = extract_skill_instructions(content)

    return SkillDetailResponse(
        name=skill["name"],
        description=skill["description"],
        path=skill["path"],
        source=skill["source"],
        content=content,
        instructions=instructions
    )


@router.post("/invoke", response_model=SkillInvokeResponse)
async def invoke_skill(request: SkillInvokeRequest):
    """Prepare a skill invocation prompt for the agent."""
    user_skills_dir = settings.get_user_skills_dir("agent")
    project_skills_dir = settings.get_project_skills_dir()

    skills = list_skills(
        user_skills_dir=user_skills_dir,
        project_skills_dir=project_skills_dir
    )

    skill = next((s for s in skills if s["name"] == request.name), None)
    if not skill:
        raise HTTPException(status_code=404, detail=f"Skill '{request.name}' not found")

    content = get_skill_content(skill["path"])
    instructions = extract_skill_instructions(content)

    # Build the prompt
    if request.task:
        prompt = f"[SKILL: {request.name}]\n\n{instructions}\n\n---\n\nUser Task: {request.task}"
    else:
        prompt = f"[SKILL: {request.name}]\n\n{instructions}"

    return SkillInvokeResponse(
        prompt=prompt,
        skill_name=request.name
    )
