"""Unified /ai/generate and /ai/evaluate."""

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)
TOKEN = get_settings().internal_api_token
HEADERS = {"X-Internal-Token": TOKEN}
BASE = "/api/v1/ai"


def _gen(**overrides):
    body = {
        "assessment_type": "aptitude_and_reasoning",
        "question_type": "mcq",
        "assessment_name": "Screening Assessment",
        "linked_job": "job-be-001",
        "duration": 30,
        "difficulty": "moderate",
        "number_of_questions": 3,
        "passing_score": 70,
    }
    body.update(overrides)
    return body


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


def test_auth_required() -> None:
    assert client.post(f"{BASE}/generate", json=_gen()).status_code == 401
    assert client.post(
        f"{BASE}/evaluate",
        json={
            "assessmentId": "a",
            "candidateId": "c",
            "assessmentType": "coding_challenge",
            "timeTaken": 1,
            "passingScore": 70,
            "questions": [{"questionId": "q1", "answer": "A", "expectedAnswer": "A"}],
        },
    ).status_code == 401
    # /ai/code/judge disabled — Platform grades coding via /ai/evaluate
    assert client.post(
        f"{BASE}/code/judge",
        json={
            "language": "python",
            "problem_statement": "sum two numbers please",
            "candidate_code": "def solve(a,b): return a+b",
        },
    ).status_code == 404


def test_invalid_assessment_type() -> None:
    res = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(assessment_type="not_a_real_kind"),
    )
    assert res.status_code == 422


def test_generate_requires_core_fields() -> None:
    res = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json={"assessment_type": "coding_challenge", "number_of_questions": 3},
    )
    assert res.status_code == 422


def test_generate_requires_linked_job_id() -> None:
    body = _gen()
    body.pop("linked_job")
    res = client.post(f"{BASE}/generate", headers=HEADERS, json=body)
    assert res.status_code == 422


def test_generate_unknown_linked_job_404() -> None:
    res = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(linked_job="job-missing"),
    )
    assert res.status_code == 404
    assert "linked_job" in res.json()["detail"]


def test_generate_loads_role_and_skills_from_job() -> None:
    res = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(
            assessment_type="coding_challenge",
            question_type="mcq",
            linked_job="job-be-001",
            number_of_questions=2,
        ),
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["linked_job"] == "job-be-001"
    assert body["role_title"] == "Backend Engineer"
    assert set(body["skills"]) >= {"Python", "FastAPI", "PostgreSQL"}


def test_generate_same_body_all_types() -> None:
    """All assessment_type values share the same 8-field request body."""
    for atype, qtype in (
        ("coding_challenge", "mcq"),
        ("aptitude_and_reasoning", "mcq"),
        ("personality_eval", "short_answer"),
        ("role_case_play", "short_answer"),
    ):
        linked = "job-pm-001" if atype == "role_case_play" else "job-be-001"
        res = client.post(
            f"{BASE}/generate",
            headers=HEADERS,
            json={
                "assessment_type": atype,
                "question_type": qtype,
                "assessment_name": f"{atype} screen",
                "linked_job": linked,
                "duration": 30,
                "difficulty": "moderate",
                "number_of_questions": 2,
                "passing_score": 70,
            },
        )
        assert res.status_code == 200, f"{atype}: {res.text}"
        body = res.json()
        assert body["assessment_type"] == atype
        assert body["linked_job"] == linked
        assert body["questions"] or body.get("tasks")


def test_generate_aptitude_mcq() -> None:
    res = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(
            assessment_type="aptitude_and_reasoning",
            question_type="mcq",
            number_of_questions=3,
            difficulty="basic",
        ),
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["assessment_type"] == "aptitude_and_reasoning"
    assert body["question_type"] == "mcq"
    assert body["assessment_name"]
    assert body["passing_score"] == 70
    assert body["aptitude_id"] or body["assessment_id"]
    assert len(body["questions"]) == 3
    assert body["answer_key"]


def test_generate_personality_eval() -> None:
    res = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(
            assessment_type="personality_eval",
            question_type="short_answer",
            assessment_name="Culture Fit",
            number_of_questions=3,
        ),
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["assessment_type"] == "personality_eval"
    assert body["assessment_id"]
    assert len(body["questions"]) == 3


def test_generate_role_case_play() -> None:
    res = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(
            assessment_type="role_case_play",
            question_type="short_answer",
            assessment_name="PM Case Play",
            linked_job="job-pm-001",
            number_of_questions=2,
            duration=45,
            difficulty="hard",
        ),
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["assessment_type"] == "role_case_play"
    assert body["case_id"]
    assert body["scenario_markdown"]
    assert body["tasks"]


def test_generate_coding_challenge() -> None:
    res = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(
            assessment_type="coding_challenge",
            question_type="mcq_and_short_answer",
            number_of_questions=2,
            duration=60,
        ),
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["assessment_type"] == "coding_challenge"
    assert body["assessment_id"]
    assert len(body["questions"]) == 2


def _questions_for_eval(gen: dict, *, wrong_every_other: bool = False) -> list[dict]:
    out = []
    for i, q in enumerate(gen.get("questions") or []):
        qid = q["id"]
        expected = (gen.get("answer_key") or {}).get(qid) or q.get("answer")
        if isinstance(expected, dict):
            expected = expected.get("answer")
        candidate = "__wrong__" if wrong_every_other and i % 2 else expected
        out.append(
            {
                "questionId": qid,
                "stem": q.get("stem"),
                "answer": candidate,
                "expectedAnswer": expected,
                "skills": (q.get("metadata") or {}).get("skills") or [],
                "maxScore": 1,
            }
        )
    return out


def test_evaluate_requires_ids() -> None:
    res = client.post(
        f"{BASE}/evaluate",
        headers=HEADERS,
        json={
            "assessmentType": "coding_challenge",
            "timeTaken": 10,
            "passingScore": 70,
            "questions": [{"questionId": "q1", "answer": "A", "expectedAnswer": "A"}],
        },
    )
    assert res.status_code == 422


def test_evaluate_persists_attempt() -> None:
    gen = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(
            assessment_type="aptitude_and_reasoning",
            number_of_questions=2,
            passing_score=50,
        ),
    ).json()
    res = client.post(
        f"{BASE}/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": gen["assessment_id"] or gen["aptitude_id"],
            "candidateId": "cand-eval-persist-001",
            "submissionId": "sub-001",
            "assessmentType": "aptitude_and_reasoning",
            "timeTaken": 500,
            "passingScore": 50,
            "questions": _questions_for_eval(gen),
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["candidate_id"] == "cand-eval-persist-001"
    assert body["submission_id"] == "sub-001"
    assert body["assessment_type"] == "aptitude_and_reasoning"
    assert body["auto_scored"] is True
    assert body["persisted"] is True
    assert body["attempt_id"]
    assert body["passed"] is True
    assert body["score_percent"] is not None


def test_evaluate_coding_challenge_partial() -> None:
    gen = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(
            assessment_type="coding_challenge",
            question_type="mcq",
            number_of_questions=4,
            linked_job="job-be-001",
            passing_score=70,
        ),
    ).json()
    res = client.post(
        f"{BASE}/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": gen["assessment_id"],
            "candidateId": "cand-eval-partial-001",
            "assessmentType": "coding_challenge",
            "timeTaken": 900,
            "passingScore": 70,
            "questions": _questions_for_eval(gen, wrong_every_other=True),
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["persisted"] is True
    skill_names = {s["skill"] for s in body["skill_scores"]}
    assert "mcq" not in {s.lower() for s in skill_names}
    assert skill_names & {"Python", "FastAPI", "PostgreSQL"}


def test_evaluate_personality_eval() -> None:
    gen = client.post(
        f"{BASE}/generate",
        headers=HEADERS,
        json=_gen(
            assessment_type="personality_eval",
            question_type="short_answer",
            assessment_name="Culture Fit",
            number_of_questions=2,
            passing_score=50,
        ),
    ).json()
    res = client.post(
        f"{BASE}/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": gen["assessment_id"],
            "candidateId": "cand-pers-001",
            "assessmentType": "personality_eval",
            "timeTaken": 600,
            "passingScore": 50,
            "questions": _questions_for_eval(gen),
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["assessment_type"] == "personality_eval"
    assert body["persisted"] is True
    assert body["passed"] is True


def test_evaluate_role_case_play() -> None:
    res = client.post(
        f"{BASE}/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": "case-play-001",
            "candidateId": "cand-case-001",
            "submissionId": "sub-001",
            "assessmentType": "role_case_play",
            "timeTaken": 1800,
            "passingScore": 70,
            "questions": [
                {
                    "questionId": "s1",
                    "stem": "Customer churn risk",
                    "answer": "Call the account and map risk",
                    "expectedAnswer": "Call the account and map risk",
                    "maxScore": 1,
                },
                {
                    "questionId": "s2",
                    "stem": "Capacity cut",
                    "answer": "Cut scope",
                    "expectedAnswer": "Cut scope",
                    "maxScore": 1,
                },
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["assessment_type"] == "role_case_play"
    assert body["score_percent"] == 100.0
    assert body["passed"] is True
    assert body["persisted"] is True
    assert body["submission_id"] == "sub-001"


# def test_code_judge() -> None:
#     """Disabled: /ai/code/judge commented out; coding uses /ai/evaluate."""
#     ...


def test_legacy_assessment_routes_removed() -> None:
    """Old assessment paths are gone — only /ai/* remains."""
    assert (
        client.post(
            "/api/v1/assessments/generate",
            headers=HEADERS,
            json={"role_title": "Dev", "kind": "mcq", "count": 1},
        ).status_code
        == 404
    )
    assert (
        client.post(
            "/api/v1/coding/judge",
            headers=HEADERS,
            json={
                "language": "python",
                "problem_statement": "Return one.",
                "candidate_code": "def solve():\n    return 1\n",
            },
        ).status_code
        == 404
    )
