"""Handler for GET /v1/models/compare endpoint.

Exposes model capability rankings for a given task type.
The MCP server (and any other consumer) calls this endpoint
to compare models without accessing the JSON database directly.
"""

from __future__ import annotations

from enum import Enum
from typing import Any

from fastapi import APIRouter, Query

from robot_resources.routing.selector import (
    DEFAULT_BASELINE,
    MODELS_DB,
    get_model_by_name,
)

router = APIRouter()


# ------------------------------------------------------------------
# Enums for validated query params
# ------------------------------------------------------------------


class CompareTaskType(str, Enum):
    coding = "coding"
    reasoning = "reasoning"
    analysis = "analysis"
    simple_qa = "simple_qa"
    creative = "creative"
    general = "general"


# ------------------------------------------------------------------
# Endpoint
# ------------------------------------------------------------------


@router.get("/v1/models/compare")
async def compare_models(
    task_type: CompareTaskType = Query(..., description="Task type to compare models for"),
    threshold: float = Query(
        0.70,
        ge=0.0,
        le=1.0,
        description="Minimum capability score (0.0–1.0)",
    ),
    provider: str | None = Query(
        None, description="Filter by provider (openai, anthropic, google)"
    ),
) -> dict[str, Any]:
    """Compare models for a given task type.

    Returns all models ranked by cost (cheapest first), with capability
    scores, savings vs baseline, and a recommendation for the cheapest
    model that meets the capability threshold.
    """
    db = MODELS_DB

    # Filter by provider if specified
    if provider is not None:
        db = [m for m in db if m["provider"] == provider]

    # Find baseline model (from full DB, not filtered)
    baseline = get_model_by_name(DEFAULT_BASELINE, MODELS_DB)
    baseline_cost = baseline["cost_per_1k_input"] if baseline else 0.0
    baseline_name = baseline["name"] if baseline else DEFAULT_BASELINE

    # Build ranked model list (sorted by cost ascending)
    ranked: list[dict[str, Any]] = []
    capable_count = 0

    sorted_models = sorted(db, key=lambda m: m["cost_per_1k_input"])

    for rank_idx, model in enumerate(sorted_models, start=1):
        cap_score = model["capabilities"].get(
            task_type.value,
            model["capabilities"].get("overall", 0),
        )
        meets = cap_score >= threshold

        if meets:
            capable_count += 1

        # Savings calculation
        if baseline_cost > 0:
            savings_pct = round(
                ((baseline_cost - model["cost_per_1k_input"]) / baseline_cost) * 100,
                1,
            )
        else:
            savings_pct = 0.0

        ranked.append(
            {
                "name": model["name"],
                "provider": model["provider"],
                "capability_score": round(cap_score, 2),
                "cost_per_1k_input": model["cost_per_1k_input"],
                "cost_per_1k_output": model["cost_per_1k_output"],
                "savings_vs_baseline_percent": savings_pct,
                "meets_threshold": meets,
                "rank": rank_idx,
            }
        )

    # Recommended = cheapest that meets threshold (first in sorted list)
    recommended: dict[str, Any] | None = None
    for m in ranked:
        if m["meets_threshold"]:
            recommended = {
                "name": m["name"],
                "provider": m["provider"],
                "capability_score": m["capability_score"],
                "cost_per_1k_input": m["cost_per_1k_input"],
                "savings_vs_baseline_percent": m["savings_vs_baseline_percent"],
            }
            break

    return {
        "task_type": task_type.value,
        "threshold": threshold,
        "baseline_model": baseline_name,
        "models": ranked,
        "recommended": recommended,
        "total_models": len(ranked),
        "capable_models": capable_count,
    }
