"""Endpoints for listing available profiles and tools."""

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException

from navi.api.deps import get_profile_registry, get_tool_registry
from navi.config import settings
from navi.core import ProfileRegistry, ToolRegistry

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


@router.get("/profiles")
async def list_profiles(
    profiles: Annotated[ProfileRegistry, Depends(get_profile_registry)],
) -> list[dict]:
    return [
        {
            "id": p.id,
            "name": p.name,
            "description": p.description,
            "enabled_tools": p.enabled_tools,
            "llm_backend": p.llm_backend,
            "model": p.model,
            "temperature": p.temperature,
            "top_k": p.top_k,
            "top_p": p.top_p,
            "max_iterations": p.max_iterations,
            "iteration_budget_enabled": p.iteration_budget_enabled,
        }
        for p in profiles.all()
    ]


@router.get("/prompts")
async def list_system_prompts(
    profiles: Annotated[ProfileRegistry, Depends(get_profile_registry)],
) -> list[dict]:
    """Return the full built system prompt for every profile, broken into sections.

    Mirrors Agent._build_system_prompt() exactly so the debug view shows
    what the model actually receives, including the dynamic profiles block.
    """
    all_profiles = profiles.all()
    persona = settings.navi_persona.strip()
    result = []

    for profile in all_profiles:
        sections = []

        if persona:
            sections.append({"label": "persona", "content": persona})

        sections.append({"label": "profile", "content": profile.system_prompt})

        other = [p for p in all_profiles if p.id != profile.id]
        if other:
            lines = [
                "## Available profiles",
                f"Current: **{profile.id}**",
            ]
            for p in other:
                desc = p.short_description or p.description
                lines.append(f"· {p.id}: {desc}")
            lines.append(
                "→ Switch profiles on your own judgment — do not ask for permission. "
                "When a task clearly fits another profile, call switch_profile immediately, "
                "then inform the user which profile is now active and why. "
                "Use list_profiles if you need details about a profile's capabilities."
            )
            sections.append({"label": "profiles block", "content": "\n".join(lines)})

        full = "\n\n---\n\n".join(s["content"] for s in sections)
        result.append({
            "profile_id": profile.id,
            "profile_name": profile.name,
            "model": profile.model,
            "enabled_tools": profile.enabled_tools,
            "sections": sections,
            "full": full,
            "total_chars": len(full),
        })

    return result


@router.get("/tools")
async def list_tools(
    tools: Annotated[ToolRegistry, Depends(get_tool_registry)],
) -> list[dict]:
    return [
        {
            "name": t.name,
            "description": t.description,
            "parameters": getattr(t, "parameters", {}),
        }
        for t in tools.all()
    ]
