"""Direct agent endpoints for specific tasks."""

from typing import Annotated

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

from pydanticai_multiagent.agents import (
    SupportResponse,
    analyst_agent,
    code_agent,
    research_agent,
    support_agent,
    writer_agent,
)
from pydanticai_multiagent.dependencies import (
    AuthDeps,
    BaseDeps,
    SearchDeps,
    create_mock_auth_deps,
    create_mock_base_deps,
    create_mock_search_deps,
)
from pydanticai_multiagent.models import AnalysisResult, ResearchResult

router = APIRouter(prefix="/agents")


# Request/Response models


class ResearchRequest(BaseModel):
    """Request for research agent."""

    query: str


class AnalysisRequest(BaseModel):
    """Request for analyst agent."""

    query: str


class CodeRequest(BaseModel):
    """Request for code agent."""

    query: str


class WriterRequest(BaseModel):
    """Request for writer agent."""

    task: str
    context: str | None = None


class SupportRequest(BaseModel):
    """Request for support agent."""

    query: str


class CodeResponse(BaseModel):
    """Response from code agent."""

    explanation: str
    code: str | None = None
    language: str | None = None
    suggestions: list[str] = []


# Dependency injection


async def get_search_deps(request: Request) -> SearchDeps:
    """Get SearchDeps for agents that need search capabilities.

    Currently uses mock dependencies for testing/development.
    """
    if hasattr(request.app.state, "deps_configured") and request.app.state.deps_configured:
        return SearchDeps(
            http_client=request.app.state.http_client,
            db=request.app.state.db,
            cache=request.app.state.cache,
            vector_store=request.app.state.vector_store,
            search_api_key=request.app.state.search_api_key,
            user_id=getattr(request.state, "user_id", "anonymous"),
        )
    return create_mock_search_deps(user_id="api-user")


async def get_base_deps(request: Request) -> BaseDeps:
    """Get BaseDeps for agents that don't need search.

    Currently uses mock dependencies for testing/development.
    """
    if hasattr(request.app.state, "deps_configured") and request.app.state.deps_configured:
        return BaseDeps(
            http_client=request.app.state.http_client,
            db=request.app.state.db,
            cache=request.app.state.cache,
            user_id=getattr(request.state, "user_id", "anonymous"),
        )
    return create_mock_base_deps(user_id="api-user")


async def get_auth_deps(request: Request) -> AuthDeps:
    """Get AuthDeps for agents that need authentication context.

    Currently uses mock dependencies for testing/development.
    """
    if hasattr(request.app.state, "deps_configured") and request.app.state.deps_configured:
        return AuthDeps(
            http_client=request.app.state.http_client,
            db=request.app.state.db,
            cache=request.app.state.cache,
            user_id=getattr(request.state, "user_id", "anonymous"),
            user_roles=getattr(request.state, "user_roles", []),
            permissions=getattr(request.state, "permissions", []),
        )
    return create_mock_auth_deps(user_id="api-user")


# Endpoints


@router.post("/research", response_model=ResearchResult)
async def run_research(
    request: ResearchRequest,
    deps: Annotated[SearchDeps, Depends(get_search_deps)],
) -> ResearchResult:
    """Run the research agent for information gathering.

    The research agent searches web and knowledge base to answer questions.
    """
    result = await research_agent.run(request.query, deps=deps)
    return result.output


@router.post("/analyze", response_model=AnalysisResult)
async def run_analysis(
    request: AnalysisRequest,
    deps: Annotated[BaseDeps, Depends(get_base_deps)],
) -> AnalysisResult:
    """Run the analyst agent for data analysis.

    The analyst agent queries databases and performs statistical analysis.
    """
    result = await analyst_agent.run(request.query, deps=deps)
    return result.output


@router.post("/code", response_model=CodeResponse)
async def run_code(
    request: CodeRequest,
    deps: Annotated[BaseDeps, Depends(get_base_deps)],
) -> CodeResponse:
    """Run the code agent for programming assistance.

    The code agent helps with coding questions, debugging, and code review.
    """
    result = await code_agent.run(request.query, deps=deps)
    output = result.output

    return CodeResponse(
        explanation=output.explanation,
        code=output.code,
        language=output.language,
        suggestions=output.suggestions,
    )


@router.post("/write")
async def run_writer(
    request: WriterRequest,
    deps: Annotated[BaseDeps, Depends(get_base_deps)],
) -> dict[str, str]:
    """Run the writer agent for content creation.

    The writer agent creates various types of content based on requirements.
    """
    prompt = request.task
    if request.context:
        prompt = f"{request.task}\n\nContext: {request.context}"

    result = await writer_agent.run(prompt, deps=deps)

    return {"content": result.output}


@router.post("/support", response_model=SupportResponse)
async def run_support(
    request: SupportRequest,
    deps: Annotated[AuthDeps, Depends(get_auth_deps)],
) -> SupportResponse:
    """Run the support agent for customer assistance.

    The support agent helps with customer inquiries, account questions,
    and escalates complex issues when needed.
    """
    result = await support_agent.run(request.query, deps=deps)
    return result.output


@router.get("/")
async def list_agents() -> dict[str, list[dict[str, str]]]:
    """List available agents and their capabilities."""
    return {
        "agents": [
            {
                "name": "research",
                "description": "Research and information gathering",
                "endpoint": "/api/v1/agents/research",
            },
            {
                "name": "analyze",
                "description": "Data analysis and insights",
                "endpoint": "/api/v1/agents/analyze",
            },
            {
                "name": "code",
                "description": "Programming assistance",
                "endpoint": "/api/v1/agents/code",
            },
            {
                "name": "write",
                "description": "Content creation",
                "endpoint": "/api/v1/agents/write",
            },
            {
                "name": "support",
                "description": "Customer support and assistance",
                "endpoint": "/api/v1/agents/support",
            },
        ]
    }
