"""Agent CRUD routes"""

from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from typing import Any

from agentkit.core.config_driven import AgentConfig
from agentkit.skills.base import SkillConfig

router = APIRouter(tags=["agents"])


class CreateAgentRequest(BaseModel):
    skill_name: str | None = None
    config: dict[str, Any] | None = None


def _get_pool(request: Request):
    return request.app.state.agent_pool


def _get_skill_registry(request: Request):
    return request.app.state.skill_registry


@router.post("/agents", status_code=201)
async def create_agent(request: CreateAgentRequest, req: Request):
    """Create an Agent instance"""
    pool = _get_pool(req)
    skill_registry = _get_skill_registry(req)

    if request.skill_name:
        # Create from registered skill
        agent = await pool.create_agent_from_skill(request.skill_name)
    elif request.config:
        # Create from config dict — try SkillConfig first, fallback to AgentConfig
        config_dict = request.config
        try:
            config = SkillConfig.from_dict(config_dict)
        except Exception:
            config = AgentConfig.from_dict(config_dict)
        agent = await pool.create_agent(config)
    else:
        raise HTTPException(status_code=422, detail="Must provide skill_name or config")

    return {
        "name": agent.name,
        "agent_type": agent.agent_type,
        "version": agent.version,
        "state": agent.status.value,
    }


@router.get("/agents")
async def list_agents(req: Request):
    """List all agents"""
    pool = _get_pool(req)
    return pool.list_agents()


@router.get("/agents/{name}")
async def get_agent(name: str, req: Request):
    """Get agent details"""
    pool = _get_pool(req)
    agent = pool.get_agent(name)
    if agent is None:
        raise HTTPException(status_code=404, detail=f"Agent '{name}' not found")
    return {
        "name": agent.name,
        "agent_type": agent.agent_type,
        "version": agent.version,
        "state": agent.status.value,
    }


@router.delete("/agents/{name}", status_code=204)
async def delete_agent(name: str, req: Request):
    """Delete an agent"""
    pool = _get_pool(req)
    agent = pool.get_agent(name)
    if agent is None:
        raise HTTPException(status_code=404, detail=f"Agent '{name}' not found")
    await pool.remove_agent(name)
