"""Candidate Performance — unified ?action= API (JD-style)."""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient

from app.config import get_settings
from app.database import SessionLocal, ensure_schema
from app.main import app
from app.models.candidate_performance import (
    CandidateAiEvaluationRecord,
    CandidateAssessmentAttemptRecord,
)
from app.services.talent.performance_scoring import (
    clamp_score_100,
    compute_overall_performance,
    map_hiring_label,
    map_interview_dimensions,
    ratio_to_score_100,
)

client = TestClient(app)
TOKEN = get_settings().internal_api_token
AUTH = {"X-Internal-Token": TOKEN}
BASE = "/api/v1/candidates"


@pytest.fixture(autouse=True)
def _clean_performance_tables():
    ensure_schema()
    db = SessionLocal()
    try:
        db.query(CandidateAiEvaluationRecord).delete()
        db.query(CandidateAssessmentAttemptRecord).delete()
        db.commit()
    finally:
        db.close()
    yield


def test_scoring_policy_clamp_and_ratio() -> None:
    assert clamp_score_100(0.85) == 85.0
    assert clamp_score_100(92) == 92.0
    assert clamp_score_100(150) == 100.0
    assert ratio_to_score_100(8, 10) == 80.0
    assert ratio_to_score_100(0, 0) is None


def test_scoring_policy_overall_renormalizes_missing() -> None:
    overall, meta = compute_overall_performance(
        mock_score=80,
        recruiter_score=None,
        assessment_score=100,
    )
    assert overall == round(80 * (0.35 / 0.60) + 100 * (0.25 / 0.60), 1)
    assert set(meta["weights_used"]) == {"mock_interview", "assessment"}
    empty, _ = compute_overall_performance(
        mock_score=None, recruiter_score=None, assessment_score=None
    )
    assert empty is None


def test_dimension_mapping_and_recommendation() -> None:
    dims = map_interview_dimensions(
        overall_01=0.9,
        category_scores=[
            {"key": "correctness", "score": 0.88},
            {"key": "depth", "score": 0.92},
            {"key": "relevance", "score": 0.8},
            {"key": "completeness", "score": 0.9},
        ],
        confidence_01=0.87,
    )
    assert dims["technical_score"] == 90.0
    assert dims["confidence_score"] == 87.0
    label, display = map_hiring_label("strong_yes")
    assert label == "strong_hire"
    assert display == "Strong Hire"


def test_auth_required() -> None:
    r = client.get(f"{BASE}/cand-1/performance")
    assert r.status_code == 401


def test_legacy_nested_paths_removed() -> None:
    assert client.get(f"{BASE}/cand-1/performance/ai", headers=AUTH).status_code == 404
    assert (
        client.get(f"{BASE}/cand-1/performance/assessments", headers=AUTH).status_code
        == 404
    )


def test_missing_results_empty_payload() -> None:
    r = client.get(f"{BASE}/cand-missing/performance", headers=AUTH)
    assert r.status_code == 200
    body = r.json()
    assert body["action"] == "overall"
    assert body["available"] is False
    assert body["overall_score"] is None
    assert body["ai_performance"]["available"] is False
    assert body["assessment"]["status"] == "not_started"

    ai = client.get(f"{BASE}/cand-missing/performance?action=ai", headers=AUTH)
    assert ai.status_code == 200
    assert ai.json()["action"] == "ai"
    assert ai.json()["available"] is False

    asa = client.get(
        f"{BASE}/cand-missing/performance?action=assessments", headers=AUTH
    )
    assert asa.status_code == 200
    assert asa.json()["action"] == "assessments"
    assert asa.json()["history"] == []


def test_ingest_ai_and_assessments_overall_blend() -> None:
    headers = {**AUTH, "X-Company-Id": "co-1"}
    ai = client.post(
        f"{BASE}/cand-emily/performance?action=ai",
        headers=headers,
        json={
            "source_type": "recruiter_interview",
            "interview_id": "int-1",
            "role_title": "Senior React Developer",
            "overall_score": 92,
            "technical_score": 89,
            "confidence_score": 87,
            "communication_score": 91,
            "culture_fit_score": 89,
            "match_percent": 94,
            "recommendation_label": "strong_hire",
            "recommendation_confidence": 90,
            "strengths": ["Strong React component modular architecture"],
            "growth_areas": ["Limited Kubernetes background"],
            "verified_skills": ["React", "TypeScript", "Node.js"],
        },
    )
    assert ai.status_code == 200
    ai_body = ai.json()
    assert ai_body["action"] == "ai"
    assert ai_body["available"] is True
    assert ai_body["score"] == 92
    assert ai_body["dimensions"]["technical"] == 89
    assert ai_body["recommendation"]["display"] == "Strong Hire"
    assert "React" in ai_body["verified_skills"]

    client.post(
        f"{BASE}/cand-emily/performance?action=ai",
        headers=headers,
        json={
            "source_key": "interview:mock-9",
            "source_type": "mock_interview",
            "overall_score": 80,
        },
    )

    asa = client.post(
        f"{BASE}/cand-emily/performance?action=assessments",
        headers=headers,
        json={
            "assessment_id": "asmt-react-1",
            "kind": "mcq",
            "score": 84,
            "status": "in_progress",
            "passed": False,
        },
    )
    assert asa.status_code == 200
    assert asa.json()["action"] == "assessments"
    assert asa.json()["latest"]["score"] == 84
    assert asa.json()["latest"]["status"] == "in_progress"

    overall = client.get(
        f"{BASE}/cand-emily/performance?action=overall", headers=headers
    ).json()
    assert overall["action"] == "overall"
    assert overall["available"] is True
    assert overall["ai_performance"]["score"] in {92, 80}
    assert overall["assessment"]["score"] == 84
    assert overall["overall_score"] == 85.8


def test_retakes_and_duplicate_upsert() -> None:
    headers = {**AUTH, "X-Company-Id": "co-1"}
    first = client.post(
        f"{BASE}/cand-retake/performance?action=assessments",
        headers=headers,
        json={
            "assessment_id": "asmt-1",
            "score": 70,
            "passed": False,
            "status": "failed",
        },
    ).json()
    assert first["latest"]["attempt_number"] == 1
    assert first["summary"]["attempt_count"] == 1

    dup = client.post(
        f"{BASE}/cand-retake/performance?action=assessments",
        headers=headers,
        json={
            "assessment_id": "asmt-1",
            "attempt_number": 1,
            "score": 72,
            "passed": False,
            "status": "failed",
        },
    ).json()
    assert dup["summary"]["attempt_count"] == 1
    assert dup["latest"]["score"] == 72

    second = client.post(
        f"{BASE}/cand-retake/performance?action=assessments",
        headers=headers,
        json={
            "assessment_id": "asmt-1",
            "score": 91,
            "passed": True,
            "status": "passed",
        },
    ).json()
    assert second["summary"]["attempt_count"] == 2
    assert second["latest"]["attempt_number"] == 2
    assert second["latest"]["score"] == 91
    assert second["summary"]["best_score"] == 91
    assert second["summary"]["latest_score"] == 91


def test_tenant_isolation() -> None:
    client.post(
        f"{BASE}/cand-shared/performance?action=ai",
        headers={**AUTH, "X-Company-Id": "co-a"},
        json={"overall_score": 88, "source_type": "ingest", "source_key": "ing-a"},
    )
    r = client.get(
        f"{BASE}/cand-shared/performance",
        headers={**AUTH, "X-Company-Id": "co-b"},
    )
    assert r.status_code == 404

    ok = client.get(
        f"{BASE}/cand-shared/performance?action=ai",
        headers={**AUTH, "X-Company-Id": "co-a"},
    )
    assert ok.status_code == 200
    assert ok.json()["score"] == 88


def test_assessment_grade_persists_when_candidate_id_set() -> None:
    headers = {**AUTH, "X-Company-Id": "co-grade"}
    grade = client.post(
        "/api/v1/ai/evaluate",
        headers=headers,
        json={
            "assessmentId": "asmt-grade-1",
            "candidateId": "cand-grade",
            "companyId": "co-grade",
            "assessmentType": "aptitude_and_reasoning",
            "timeTaken": 300,
            "passingScore": 70,
            "questions": [
                {
                    "questionId": "q1",
                    "answer": "A",
                    "expectedAnswer": "A",
                    "maxScore": 1,
                },
                {
                    "questionId": "q2",
                    "answer": "B",
                    "expectedAnswer": "B",
                    "maxScore": 1,
                },
            ],
        },
    )
    assert grade.status_code == 200
    body = grade.json()
    assert body["passed"] is True
    assert body["persisted"] is True

    hist = client.get(
        f"{BASE}/cand-grade/performance?action=assessments",
        headers=headers,
    ).json()
    assert hist["available"] is True
    assert hist["latest"]["assessment_id"] == "asmt-grade-1"
    assert hist["latest"]["score"] == 100.0
    assert hist["latest"]["status"] == "passed"
