"""Stateless final-evaluation — concise response + scoring consistency."""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient

from app.config import get_settings
from app.main import app

client = TestClient(app)
HEADERS = {"X-Internal-Token": get_settings().internal_api_token}

JD = (
    "Build APIs in Python/FastAPI, own PostgreSQL schema design, "
    "and mentor junior engineers on system design."
)


@pytest.fixture(autouse=True)
def _force_local(monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setattr("app.llm._provider_available", lambda _name: False)


def _base(*, include_details: bool = False, **extra):
    body = {
        "interview_id": "fe-1",
        "candidate_id": "cand-fe-1",
        "interview_mode": "text",
        "role_title": "Backend Engineer",
        "job_description": JD,
        "required_skills": ["FastAPI", "PostgreSQL", "Redis"],
        "include_details": include_details,
        "qa_items": [
            {
                "question_id": "q-1",
                "question": "Describe your FastAPI production experience.",
                "answer": (
                    "I design FastAPI services with Redis caching, measure p95 latency, "
                    "and own PostgreSQL schema migrations with clear trade-offs."
                ),
                "turn_index": 0,
                "skill_tags": ["FastAPI"],
                "category_keys": ["correctness", "depth"],
            },
            {
                "question_id": "q-2",
                "question": "How do you design PostgreSQL schemas?",
                "answer": "I used Redis.",
                "turn_index": 1,
                "skill_tags": ["PostgreSQL"],
                "category_keys": ["relevance", "completeness"],
            },
        ],
    }
    body.update(extra)
    return body


def test_session_routes_removed() -> None:
    assert (
        client.post("/api/v1/interviews/sessions/start", headers=HEADERS, json={}).status_code
        == 404
    )


def test_default_response_is_concise_without_redundant_fields() -> None:
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json=_base(
            candidate_id="cand-1",
            candidate_name="Alex Rivera",
            turn_scores=[
                {"question_id": "q-1", "score": 0.9, "provenance": "supplied"},
                {"question_id": "q-2", "score": 0.5, "provenance": "supplied"},
            ],
        ),
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["candidate_name"] == "Alex Rivera"
    assert body["role_title"] == "Backend Engineer"
    assert body["interview_mode"] == "text"
    assert body["overall_score"] == pytest.approx(0.7, abs=0.01)
    assert body["summary"]
    assert len(body["strengths"]) <= 3
    assert len(body["improvement_areas"]) <= 3
    assert body["recommendation"]["requires_human_review"] is True
    assert body["recommendation"]["action"]
    assert body["recommendation"]["reason"]
    assert body["question_count"] == 2
    assert body["correlation_id"] is None or True
    # Review UI: per-question AI Explanation (how it should be answered)
    assert len(body["questions"]) == 2
    for q in body["questions"]:
        assert q.get("question")
        assert q.get("answer") is not None
        assert q.get("ai_explanation")
        assert len(q["ai_explanation"]) >= 40
        assert "score" in q
    # Redundant / verbose fields omitted by default
    assert body.get("details") is None
    assert "aggregated" not in body
    assert "report" not in body
    assert "skill_gap" not in body
    assert "hiring_fit" not in body
    assert "markdown" not in body
    assert "text_communication" not in body
    assert "media_metrics" not in body
    # not_assessed skills must not appear as improvement weaknesses
    skills = {s["skill"]: s for s in body["skills"]}
    assert "Redis" in skills
    assert skills["Redis"]["status"] == "not_assessed"
    assert skills["Redis"]["score"] is None
    for area in body["improvement_areas"]:
        assert "insufficient evidence" not in area.lower()
        assert "Redis" not in area or "not_assessed" in area.lower()


def test_scores_unchanged_with_and_without_details() -> None:
    payload = _base(
        turn_scores=[
            {
                "question_id": "q-1",
                "score": 0.9,
                "dimensions": {"correctness": 0.9, "depth": 0.85},
                "provenance": "supplied",
            },
            {
                "question_id": "q-2",
                "score": 0.3,
                "dimensions": {"relevance": 0.3, "completeness": 0.25},
                "provenance": "supplied",
            },
        ],
    )
    slim = client.post(
        "/api/v1/interviews/final-evaluation", headers=HEADERS, json=payload
    ).json()
    detailed = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={**payload, "include_details": True},
    ).json()
    assert slim["overall_score"] == detailed["overall_score"]
    assert slim["overall_score"] == pytest.approx(0.6, abs=0.01)
    assert slim["question_count"] == detailed["question_count"] == 2
    assert detailed["details"] is not None
    assert detailed["details"]["aggregated"]["overall_provenance"] == (
        "calculated_from_supplied"
    )
    assert detailed["details"]["aggregation_fallback"] == (
        "mean_of_supplied_question_scores"
    )


def test_three_supplied_scores_mean_and_details(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    calls = {"n": 0}
    from app.services.interviews import final_evaluation as fe

    real = fe.InterviewsService.evaluate_answer

    async def counting(self, payload):
        calls["n"] += 1
        return await real(self, payload)

    monkeypatch.setattr(fe.InterviewsService, "evaluate_answer", counting)

    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "correlation_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "interview_id": "fe-jane-001",
            "candidate_id": "cand-jane-001",
            "interview_mode": "text",
            "role_title": "Backend Engineer",
            "job_description": JD,
            "include_details": True,
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "FastAPI experience?",
                    "answer": "strong",
                    "category_keys": ["correctness"],
                    "skill_tags": ["FastAPI"],
                },
                {
                    "question_id": "q-2",
                    "question": "PostgreSQL schemas?",
                    "answer": "ok",
                    "category_keys": ["depth"],
                    "skill_tags": ["PostgreSQL"],
                },
                {
                    "question_id": "q-3",
                    "question": "Redis caching?",
                    "answer": "weak",
                    "category_keys": ["relevance"],
                    "skill_tags": ["Redis"],
                },
            ],
            "turn_scores": [
                {
                    "question_id": "q-1",
                    "score": 0.9,
                    "dimensions": {"correctness": 0.9, "depth": 0.85},
                    "provenance": "supplied",
                },
                {
                    "question_id": "q-2",
                    "score": 0.7,
                    "dimensions": {"depth": 0.7, "completeness": 0.65},
                    "provenance": "supplied",
                },
                {
                    "question_id": "q-3",
                    "score": 0.3,
                    "dimensions": {"relevance": 0.3, "correctness": 0.25},
                    "provenance": "supplied",
                },
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert calls["n"] == 0
    assert body["overall_score"] == pytest.approx(0.633, abs=0.01)
    assert body["question_count"] == 3
    assert body["candidate_id"] == "cand-jane-001"
    assert body["correlation_id"] == "3fa85f64-5717-4562-b3fc-2c963f66afa6"
    assert body["recommendation"]["requires_human_review"] is True
    qs = body["details"]["aggregated"]["question_scores"]
    scores = {q["question_id"]: q for q in qs}
    assert scores["q-1"]["score"] == 0.9
    assert scores["q-2"]["score"] == 0.7
    assert scores["q-3"]["score"] == 0.3
    assert all(q["provenance"] == "supplied" for q in qs)
    assert body["details"]["overall_provenance"] == "calculated_from_supplied"


def test_unequal_category_scores_from_dimensions() -> None:
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": "fe-unequal",
            "candidate_id": "cand-unequal",
            "interview_mode": "text",
            "role_title": "Backend Engineer",
            "job_description": JD,
            "include_details": True,
            "category_weights": [
                {"key": "correctness", "weight": 2.0},
                {"key": "relevance", "weight": 1.0},
                {"key": "depth", "weight": 1.0},
            ],
            "qa_items": [
                {"question_id": "q-1", "question": "Q1", "answer": "A1"},
                {"question_id": "q-2", "question": "Q2", "answer": "A2"},
            ],
            "turn_scores": [
                {
                    "question_id": "q-1",
                    "score": 0.9,
                    "dimensions": {"correctness": 0.9, "relevance": 0.5},
                    "provenance": "supplied",
                },
                {
                    "question_id": "q-2",
                    "score": 0.4,
                    "dimensions": {"correctness": 0.3, "depth": 0.8},
                    "provenance": "supplied",
                },
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    cats = {c["key"]: c for c in body["categories"]}
    assert cats["correctness"]["score"] == pytest.approx(0.6, abs=0.01)
    assert cats["relevance"]["score"] == pytest.approx(0.5, abs=0.01)
    assert cats["depth"]["score"] == pytest.approx(0.8, abs=0.01)
    assert body["overall_score"] == pytest.approx(0.65, abs=0.01)
    assert body["details"]["aggregated"]["weights_effective"]["correctness"] == (
        pytest.approx(0.5, abs=0.01)
    )


def test_score_band_derived_and_dimension_categories_not_filtered() -> None:
    """score_band filled from score; dimensions count even if category_keys omit a key."""
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": "fe-band-rel",
            "candidate_id": "cand-band-rel",
            "interview_mode": "text",
            "role_title": "Backend Engineer",
            "job_description": JD,
            "include_details": True,
            "category_weights": [
                {"key": "correctness", "weight": 2.0, "label": "Correctness"},
                {"key": "depth", "weight": 1.0, "label": "Depth"},
                {"key": "relevance", "weight": 1.0, "label": "Relevance"},
            ],
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "How would you design a cache?",
                    "answer": "Redis cache-aside with TTLs and monitoring.",
                    "category_keys": ["correctness", "depth"],
                }
            ],
            "turn_scores": [
                {
                    "question_id": "q-1",
                    "score": 0.85,
                    "dimensions": {
                        "correctness": 0.9,
                        "depth": 0.8,
                        "relevance": 0.85,
                    },
                    "provenance": "supplied",
                }
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["questions"][0]["score_band"] == "strong"
    cats = {c["key"]: c["score"] for c in body["categories"]}
    assert cats["relevance"] == pytest.approx(0.85)
    assert cats["correctness"] == pytest.approx(0.9)
    assert body["details"] is not None
    detail_cats = {
        c["key"]: c["score"]
        for c in body["details"]["aggregated"]["category_scores"]
    }
    assert detail_cats["relevance"] == pytest.approx(0.85)


def test_missing_category_null_not_zero() -> None:
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": "fe-missing-cat",
            "candidate_id": "cand-missing-cat",
            "interview_mode": "text",
            "role_title": "Backend Engineer",
            "job_description": JD,
            "include_details": True,
            "category_weights": [
                {"key": "correctness", "weight": 1.0},
                {"key": "depth", "weight": 1.0},
                {"key": "completeness", "weight": 3.0},
            ],
            "qa_items": [{"question_id": "q-1", "question": "Q?", "answer": "A"}],
            "turn_scores": [
                {
                    "question_id": "q-1",
                    "score": 0.8,
                    "dimensions": {"correctness": 0.8, "depth": 0.4},
                    "provenance": "supplied",
                }
            ],
        },
    )
    assert res.status_code == 200
    body = res.json()
    cats = {c["key"]: c for c in body["categories"]}
    assert cats["completeness"]["score"] is None
    assert "completeness" in body["details"]["aggregated"]["missing_categories"]
    assert body["overall_score"] == pytest.approx(0.8, abs=0.01)


def test_unavailable_skill_not_assessed_not_weakness() -> None:
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": "fe-k8s",
            "candidate_id": "cand-k8s",
            "interview_mode": "text",
            "role_title": "Backend Engineer",
            "job_description": JD,
            "required_skills": ["Kubernetes"],
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "Tell me about APIs.",
                    "answer": "I build REST APIs with clear ownership.",
                },
                {
                    "question_id": "q-2",
                    "question": "How do you test services?",
                    "answer": "Unit tests plus load tests for p95 latency.",
                },
            ],
            "turn_scores": [
                {"question_id": "q-1", "score": 0.8, "provenance": "supplied"},
                {"question_id": "q-2", "score": 0.8, "provenance": "supplied"},
            ],
        },
    )
    assert res.status_code == 200
    body = res.json()
    skills = {s["skill"]: s for s in body["skills"]}
    assert skills["Kubernetes"]["status"] == "not_assessed"
    assert skills["Kubernetes"]["score"] is None
    assert body["recommendation"]["requires_human_review"] is True
    for area in body["improvement_areas"]:
        assert "Kubernetes" not in area or "not_assessed" in area.lower()


def test_skill_tags_assessed_vs_not_assessed() -> None:
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": "fe-skill-tags",
            "candidate_id": "cand-skill-tags",
            "interview_mode": "text",
            "role_title": "Backend Engineer",
            "job_description": JD,
            "required_skills": ["FastAPI", "Redis"],
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "Describe your FastAPI production experience.",
                    "answer": "Built FastAPI services with clear routers.",
                }
            ],
            "turn_scores": [
                {"question_id": "q-1", "score": 0.9, "provenance": "supplied"}
            ],
        },
    )
    assert res.status_code == 200
    body = res.json()
    skills = {s["skill"]: s for s in body["skills"]}
    assert skills["FastAPI"]["status"] in {"assessed", "needs_improvement"}
    assert skills["FastAPI"]["score"] == pytest.approx(0.9)
    assert skills["Redis"]["status"] == "not_assessed"
    assert skills["Redis"]["score"] is None


def test_include_details_exposes_diagnostics() -> None:
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json=_base(
            include_details=True,
            interview_mode="voice",
            turn_scores=[
                {"question_id": "q-1", "score": 0.9, "provenance": "supplied"},
                {"question_id": "q-2", "score": 0.5, "provenance": "supplied"},
            ],
        ),
    )
    assert res.status_code == 200
    body = res.json()
    assert body["details"] is not None
    assert body["details"]["aggregated"]["question_count"] == 2
    assert body["details"]["hiring_fit"]["formula"]
    media = {m["key"]: m for m in body["details"]["media_metrics"]}
    assert media["voice_delivery"]["provenance"] == "unavailable"


def test_text_mode_communication_in_details_only() -> None:
    payload = {
        "interview_id": "fe-text-comm",
        "candidate_id": "cand-text-comm",
        "interview_mode": "text",
        "role_title": "Backend Engineer",
        "job_description": JD,
        "qa_items": [
            {
                "question_id": "q-1",
                "question": "How do you design caching?",
                "answer": (
                    "First I measure p95 latency, then introduce Redis with TTLs, "
                    "invalidate on writes, and document trade-offs clearly."
                ),
            }
        ],
        "turn_scores": [
            {"question_id": "q-1", "score": 0.85, "provenance": "supplied"}
        ],
    }
    slim = client.post(
        "/api/v1/interviews/final-evaluation", headers=HEADERS, json=payload
    ).json()
    assert slim.get("details") is None
    assert "text_communication" not in slim

    detailed = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={**payload, "include_details": True},
    ).json()
    text = {m["key"]: m for m in detailed["details"]["text_communication"]}
    for key in ("text_clarity", "text_structure", "text_organization", "text_relevance"):
        assert text[key]["provenance"] != "unavailable"
        assert text[key]["score"] is not None
    assert slim["overall_score"] == detailed["overall_score"]
    assert detailed["details"]["aggregated"]["question_scores"][0]["ai_explanation"]
    assert detailed["questions"][0]["ai_explanation"]


def test_ai_explanation_how_question_should_be_answered() -> None:
    """Review UI: AI Explanation describes the intended approach, not score rationale."""
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": "fe-ai-expl",
            "candidate_id": "cand-ai-expl",
            "interview_mode": "text",
            "role_title": "Frontend Engineer",
            "job_description": "Build accessible React apps with TypeScript.",
            "required_skills": ["React", "TypeScript"],
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "Which hook is used to manage state in a functional component?",
                    "answer": (
                        "I'm a frontend engineer with four years of experience building "
                        "accessible, responsive web applications."
                    ),
                }
            ],
            "turn_scores": [
                {"question_id": "q-1", "score": 0.2, "provenance": "supplied"}
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert len(body["questions"]) == 1
    q = body["questions"][0]
    assert q["question_id"] == "q-1"
    assert "hook" in (q["question"] or "").lower()
    assert q["answer"]
    expl = (q["ai_explanation"] or "").lower()
    assert expl
    # Concept guide — how it should be answered (not just "score is low")
    assert "score" not in expl or "react" in expl or "state" in expl or "hook" in expl
    assert any(
        token in expl
        for token in ("react", "state", "hook", "declarative", "component", "approach")
    )
