"""Sovereignty metrics dashboard routes.

Provides API endpoints and HTMX partials for tracking research
sovereignty progress against graduation targets.

Refs: #981
"""

import logging
from typing import Any

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse

from config import settings
from dashboard.templating import templates
from infrastructure.sovereignty_metrics import (
    GRADUATION_TARGETS,
    get_sovereignty_store,
)

logger = logging.getLogger(__name__)

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


@router.get("/metrics")
async def sovereignty_metrics_api() -> dict[str, Any]:
    """JSON API: full sovereignty metrics summary with trends."""
    store = get_sovereignty_store()
    summary = store.get_summary()
    alerts = store.get_alerts(unacknowledged_only=True)
    return {
        "metrics": summary,
        "alerts": alerts,
        "targets": GRADUATION_TARGETS,
        "cost_threshold": settings.sovereignty_api_cost_alert_threshold,
    }


@router.get("/metrics/panel", response_class=HTMLResponse)
async def sovereignty_metrics_panel(request: Request) -> HTMLResponse:
    """HTMX partial: sovereignty metrics progress panel."""
    store = get_sovereignty_store()
    summary = store.get_summary()
    alerts = store.get_alerts(unacknowledged_only=True)

    return templates.TemplateResponse(
        request,
        "partials/sovereignty_metrics.html",
        {
            "metrics": summary,
            "alerts": alerts,
            "targets": GRADUATION_TARGETS,
        },
    )


@router.get("/alerts")
async def sovereignty_alerts_api() -> dict[str, Any]:
    """JSON API: sovereignty alerts."""
    store = get_sovereignty_store()
    return {
        "alerts": store.get_alerts(unacknowledged_only=False),
        "unacknowledged": store.get_alerts(unacknowledged_only=True),
    }


@router.post("/alerts/{alert_id}/acknowledge")
async def acknowledge_alert(alert_id: int) -> dict[str, bool]:
    """Acknowledge a sovereignty alert."""
    store = get_sovereignty_store()
    success = store.acknowledge_alert(alert_id)
    return {"success": success}
