"""
Metrics endpoint for v1/Gateway parity analysis.

Returns gateway metrics and parity summary for monitoring the migration.
Only available when shadow mode is enabled.

RESTRICTED: Only accessible to INTERNAL, DEV, or ENTERPRISE tier accounts.

See: dynamic-purring-sutherland.md for migration plan.
"""

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse

from .deps import require_api_key, ApiRequestContext
from ...settings import (
    V1_MATCH_USE_GATEWAY,
    V1_MATCH_GATEWAY_SHADOW_MODE,
    V1_MATCH_GATEWAY_KILL_SWITCH,
    V1_MATCH_GATEWAY_SHADOW_SAMPLE_PCT,
)

router = APIRouter(prefix="/api/v1/match", tags=["match-metrics"])

# Tiers allowed to access gateway metrics
_ELEVATED_TIERS = frozenset({"INTERNAL", "DEV", "ENTERPRISE", "ADMIN"})


def _require_elevated_tier(api_ctx: ApiRequestContext = Depends(require_api_key)) -> ApiRequestContext:
    """Require elevated tier (INTERNAL, DEV, ENTERPRISE, ADMIN) for access."""
    tier = (api_ctx.tier or "").upper()
    if tier not in _ELEVATED_TIERS:
        raise HTTPException(
            status_code=403,
            detail={
                "error": "FORBIDDEN",
                "message": "This endpoint requires elevated tier access (INTERNAL, DEV, ENTERPRISE, or ADMIN)",
            },
        )
    return api_ctx


@router.get("/gateway-metrics")
async def get_gateway_metrics(api_ctx: ApiRequestContext = Depends(_require_elevated_tier)):
    """
    Returns parity metrics for v1/Gateway comparison.

    Only returns meaningful data when shadow mode is enabled.
    Aggregate parity analysis should be done via log queries.
    """
    try:
        from ...services.match_gateway import MatchGateway

        gateway = await MatchGateway.create()
        gateway_metrics = gateway.get_metrics() if hasattr(gateway, 'get_metrics') else {}
    except Exception:
        gateway_metrics = {"error": "Gateway not available"}

    return JSONResponse(content={
        "config": {
            "use_gateway": V1_MATCH_USE_GATEWAY,
            "shadow_mode": V1_MATCH_GATEWAY_SHADOW_MODE,
            "kill_switch": V1_MATCH_GATEWAY_KILL_SWITCH,
            "shadow_sample_pct": V1_MATCH_GATEWAY_SHADOW_SAMPLE_PCT,
        },
        "gateway_metrics": gateway_metrics,
        "parity_analysis": {
            "note": "Query v1_gateway_parity logs for detailed parity analysis",
            "example_query": """
SELECT
    DATE(timestamp) as day,
    COUNT(*) as requests,
    AVG(score_delta) as avg_score_delta,
    SUM(CASE WHEN recommendation_match THEN 1 ELSE 0 END)::float / COUNT(*) as parity_rate
FROM logs
WHERE log_name = 'v1_gateway_parity'
GROUP BY DATE(timestamp);
            """.strip(),
        },
    })
