"""Score and history endpoints.

GET /v1/score/{agent_id}   — Latest drift score
GET /v1/history/{agent_id} — Paginated drift history
"""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from kredo_drift.server.auth import AuthenticatedAgent, require_api_key
from kredo_drift.server.db.models import Agent, DriftTestRecord, Baseline
from kredo_drift.server.db.session import get_db

router = APIRouter(tags=["score"])


@router.get("/score/{agent_id}")
async def get_score(
    agent_id: str,
    auth: AuthenticatedAgent = Depends(require_api_key),
    db: AsyncSession = Depends(get_db),
):
    """Get the latest drift score for an agent."""
    agent_result = await db.execute(
        select(Agent).where(Agent.agent_id == agent_id)
    )
    agent = agent_result.scalar_one_or_none()
    if not agent:
        raise HTTPException(status_code=404, detail="Agent not found")

    test_result = await db.execute(
        select(DriftTestRecord)
        .where(DriftTestRecord.agent_pubkey == agent.pubkey)
        .order_by(DriftTestRecord.created_at.desc())
        .limit(1)
    )
    test = test_result.scalar_one_or_none()
    if not test:
        raise HTTPException(status_code=404, detail="No drift tests found")

    # Severity label
    score = test.score
    if score <= 15:
        severity = "Stable"
    elif score <= 35:
        severity = "Shifting"
    elif score <= 60:
        severity = "Drifting"
    elif score <= 85:
        severity = "Diverged"
    else:
        severity = "Unrecognizable"

    return {
        "agent_id": agent_id,
        "score": test.score,
        "severity": severity,
        "classification": test.classification,
        "dimension_scores": test.dimension_scores,
        "test_hash": test.content_hash,
        "baseline_hash": test.baseline_hash,
        "tested_at": test.created_at.isoformat(),
    }


@router.get("/history/{agent_id}")
async def get_history(
    agent_id: str,
    limit: int = Query(default=20, ge=1, le=100),
    offset: int = Query(default=0, ge=0),
    auth: AuthenticatedAgent = Depends(require_api_key),
    db: AsyncSession = Depends(get_db),
):
    """Get paginated drift history for an agent."""
    agent_result = await db.execute(
        select(Agent).where(Agent.agent_id == agent_id)
    )
    agent = agent_result.scalar_one_or_none()
    if not agent:
        raise HTTPException(status_code=404, detail="Agent not found")

    tests_result = await db.execute(
        select(DriftTestRecord)
        .where(DriftTestRecord.agent_pubkey == agent.pubkey)
        .order_by(DriftTestRecord.created_at.desc())
        .offset(offset)
        .limit(limit)
    )
    tests = tests_result.scalars().all()

    return {
        "agent_id": agent_id,
        "count": len(tests),
        "offset": offset,
        "tests": [
            {
                "content_hash": t.content_hash,
                "score": t.score,
                "classification": t.classification,
                "dimension_scores": t.dimension_scores,
                "tested_at": t.created_at.isoformat(),
            }
            for t in tests
        ],
    }
