"""Timed puzzles/aptitude + AI assessments — auto-score, timing, skills, coding exec."""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient

from app.config import get_settings
from app.main import app
from app.services.assessments.code_exec import run_python_tests
from app.services.assessments.grading import (
    auto_grade_answers,
    evaluate_timing,
    normalize_answer_key,
)

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


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


# --- unit: grading helpers ---


def test_auto_grade_exact_match_and_skill_scores() -> None:
    key = normalize_answer_key(
        answer_key={
            "q-1": {"answer": "A", "skills": ["logic"], "max_score": 1},
            "q-2": {"answer": "B", "skills": ["patterns"], "max_score": 1},
        }
    )
    items, total, max_total, skills, passed = auto_grade_answers(
        answers=[
            {"question_id": "q-1", "selected": "A"},
            {"question_id": "q-2", "selected": "A"},
        ],
        answer_key=key,
    )
    assert total == 1.0
    assert max_total == 2.0
    assert passed is False
    assert items[0].is_correct is True
    assert items[1].is_correct is False
    assert {s.skill for s in skills} == {"logic", "patterns"}
    assert next(s for s in skills if s.skill == "logic").correct == 1


def test_timing_overtime_fails() -> None:
    t = evaluate_timing(time_limit_minutes=20, time_taken_seconds=1300)
    assert t.timing_ok is False
    assert t.overtime_seconds == 100


def test_python_test_exec_pass() -> None:
    code = "def solve(a, b):\n    return a + b\n"
    results, ratio, failing = run_python_tests(
        code,
        [
            {"name": "sum", "args": [2, 3], "expected": 5},
            {"name": "zero", "args": [0, 0], "expected": 0},
        ],
    )
    assert ratio == 1.0
    assert failing == []
    assert all(r["passed"] for r in results)


def test_python_test_exec_blocks_import() -> None:
    code = "import os\ndef solve():\n    return 1\n"
    results, ratio, failing = run_python_tests(
        code, [{"name": "t", "args": None, "expected": 1}]
    )
    assert ratio == 0.0
    assert failing
    assert "import" in (results[0].get("error") or "").lower()


# --- API: puzzles ---


def test_aptitude_generate_includes_answer_key_and_skills() -> None:
    res = client.post(
        "/api/v1/ai/generate",
        headers=HEADERS,
        json={
            "assessment_type": "aptitude_and_reasoning",
            "question_type": "mcq",
            "assessment_name": "Logic Screen",
            "linked_job": "job-general-001",
            "duration": 15,
            "difficulty": "basic",
            "number_of_questions": 3,
            "passing_score": 60,
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["duration"] == 15
    assert "logic" in body["skills"] or body["skills"]
    assert len(body["questions"]) == 3
    assert body["answer_key"]
    q0 = body["questions"][0]
    assert q0["answer"]
    assert q0["metadata"].get("skills")


def _eval_questions(gen: dict, *, flip_last: bool = False) -> list[dict]:
    out = []
    qs = gen.get("questions") or []
    for i, q in enumerate(qs):
        qid = q["id"]
        expected = (gen.get("answer_key") or {}).get(qid) or q.get("answer")
        if isinstance(expected, dict):
            expected = expected.get("answer")
        ans = "Z" if flip_last and i == len(qs) - 1 else expected
        out.append(
            {
                "questionId": qid,
                "stem": q.get("stem"),
                "answer": ans,
                "expectedAnswer": expected,
                "skills": (q.get("metadata") or {}).get("skills") or [],
                "maxScore": 1,
            }
        )
    return out


def test_aptitude_grade_auto_score_and_timing() -> None:
    gen = client.post(
        "/api/v1/ai/generate",
        headers=HEADERS,
        json={
            "assessment_type": "aptitude_and_reasoning",
            "question_type": "mcq",
            "assessment_name": "Logic",
            "linked_job": "job-general-001",
            "duration": 10,
            "difficulty": "basic",
            "number_of_questions": 2,
            "passing_score": 60,
        },
    ).json()
    res = client.post(
        "/api/v1/ai/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": gen["assessment_id"] or gen["aptitude_id"],
            "candidateId": "cand-score-1",
            "assessmentType": "aptitude_and_reasoning",
            "timeTaken": 500,
            "passingScore": 60,
            "questions": _eval_questions(gen, flip_last=True),
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["auto_scored"] is True
    assert body["total_score"] == 1.0
    assert body["max_total_score"] == 2.0
    assert body["passed"] is False  # 50% < 60%
    assert body["persisted"] is True
    assert body["skill_scores"]


def test_aptitude_grade_all_correct_passes() -> None:
    gen = client.post(
        "/api/v1/ai/generate",
        headers=HEADERS,
        json={
            "assessment_type": "aptitude_and_reasoning",
            "question_type": "mcq",
            "assessment_name": "Logic",
            "linked_job": "job-general-001",
            "duration": 5,
            "difficulty": "basic",
            "number_of_questions": 2,
            "passing_score": 60,
        },
    ).json()
    res = client.post(
        "/api/v1/ai/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": gen["assessment_id"] or gen["aptitude_id"],
            "candidateId": "cand-score-2",
            "assessmentType": "aptitude_and_reasoning",
            "timeTaken": 400,
            "passingScore": 60,
            "questions": _eval_questions(gen),
        },
    )
    body = res.json()
    assert body["auto_scored"] is True
    assert body["total_score"] == 2.0
    assert body["passed"] is True
    assert body["persisted"] is True


# --- API: aptitude ---


def test_aptitude_generate_and_grade_skill_report() -> None:
    gen = client.post(
        "/api/v1/ai/generate",
        headers=HEADERS,
        json={
            "assessment_type": "aptitude_and_reasoning",
            "question_type": "mcq",
            "assessment_name": "Aptitude",
            "linked_job": "job-general-001",
            "duration": 20,
            "difficulty": "basic",
            "number_of_questions": 4,
            "passing_score": 60,
        },
    )
    assert gen.status_code == 200
    g = gen.json()
    assert g["answer_key"]
    assert g["skills"]  # from linked job

    res = client.post(
        "/api/v1/ai/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": g["assessment_id"] or g["aptitude_id"],
            "candidateId": "cand-score-3",
            "assessmentType": "aptitude_and_reasoning",
            "timeTaken": 600,
            "passingScore": 60,
            "questions": _eval_questions(g),
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["auto_scored"] is True
    assert body["passed"] is True
    assert body["total_score"] == 4.0
    assert body["persisted"] is True
    assert len(body["skill_scores"]) >= 1


# --- API: assessments (coding / personality) ---


def test_assessments_coding_generate_and_grade() -> None:
    gen = client.post(
        "/api/v1/ai/generate",
        headers=HEADERS,
        json={
            "assessment_type": "coding_challenge",
            "question_type": "mcq",
            "assessment_name": "Technical Screen",
            "linked_job": "job-be-001",
            "duration": 30,
            "difficulty": "hard",
            "number_of_questions": 3,
            "passing_score": 70,
        },
    )
    assert gen.status_code == 200
    g = gen.json()
    assert g["assessment_type"] == "coding_challenge"
    assert g["duration"] == 30
    assert g["answer_key"]
    assert g["rubric"].get("skills") or g["skills"]

    res = client.post(
        "/api/v1/ai/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": g["assessment_id"],
            "candidateId": "cand-score-4",
            "assessmentType": "coding_challenge",
            "timeTaken": 1000,
            "passingScore": 70,
            "questions": _eval_questions(g),
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["auto_scored"] is True
    assert body["passed"] is True
    assert body["skill_scores"]
    assert body["persisted"] is True


def test_assessments_personality_generate() -> None:
    res = client.post(
        "/api/v1/ai/generate",
        headers=HEADERS,
        json={
            "assessment_type": "personality_eval",
            "question_type": "mcq",
            "assessment_name": "Culture Fit",
            "linked_job": "job-clinical-001",
            "duration": 30,
            "difficulty": "moderate",
            "number_of_questions": 2,
            "passing_score": 50,
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["assessment_type"] == "personality_eval"
    assert body["skills"] or body["questions"]


# --- API: coding with test exec ---


# /ai/code/judge disabled — coding_challenge graded via /ai/evaluate
# def test_coding_judge_executes_python_tests() -> None: ...
# def test_coding_judge_fails_wrong_solution() -> None: ...


def test_coding_judge_route_disabled() -> None:
    res = client.post(
        "/api/v1/ai/code/judge",
        headers=HEADERS,
        json={
            "language": "python",
            "problem_statement": "Return the sum of two numbers.",
            "candidate_code": "def solve(a, b):\n    return a + b\n",
            "execute_tests": True,
        },
    )
    assert res.status_code == 404


# --- API: answers evaluate with skills ---


def test_answers_evaluate_auto_skill_scores() -> None:
    res = client.post(
        "/api/v1/ai/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": "asm-skills",
            "candidateId": "cand-skills",
            "assessmentType": "aptitude_and_reasoning",
            "timeTaken": 120,
            "passingScore": 50,
            "questions": [
                {
                    "questionId": "q1",
                    "stem": "2+2?",
                    "answer": "4",
                    "expectedAnswer": "4",
                    "maxScore": 1,
                    "skills": ["numeracy"],
                },
                {
                    "questionId": "q2",
                    "stem": "Capital of France?",
                    "answer": "Lyon",
                    "expectedAnswer": "Paris",
                    "maxScore": 1,
                    "skills": ["geography"],
                },
            ],
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["auto_scored"] is True
    assert body["total_score"] == 1.0
    assert body["max_total_score"] == 2.0
    assert body["persisted"] is True
    skills = {s["skill"]: s for s in body["skill_scores"]}
    assert skills["numeracy"]["correct"] == 1
    assert skills["geography"]["correct"] == 0


def test_existing_stub_paths_still_work() -> None:
    """Regression: unified /ai hub kinds succeed with minimal payloads."""
    assert (
        client.post(
            "/api/v1/ai/generate",
            headers=HEADERS,
            json={
            "assessment_type": "aptitude_and_reasoning",
            "question_type": "mcq",
            "assessment_name": "Logic",
            "linked_job": "job-general-001",
            "duration": 20,
            "difficulty": "basic",
            "number_of_questions": 2,
            "passing_score": 60,
        },
        ).status_code
        == 200
    )
    assert (
        client.post(
            "/api/v1/ai/generate",
            headers=HEADERS,
            json={
            "assessment_type": "aptitude_and_reasoning",
            "question_type": "mcq",
            "assessment_name": "Aptitude",
            "linked_job": "job-general-001",
            "duration": 30,
            "difficulty": "basic",
            "number_of_questions": 3,
            "passing_score": 60,
        },
        ).status_code
        == 200
    )
    assert (
        client.post(
            "/api/v1/ai/generate",
            headers=HEADERS,
            json={
            "assessment_type": "coding_challenge",
            "question_type": "mcq",
            "assessment_name": "MCQ Screen",
            "linked_job": "job-be-001",
            "duration": 30,
            "difficulty": "moderate",
            "number_of_questions": 5,
            "passing_score": 70,
        },
        ).status_code
        == 200
    )
    assert (
        client.post(
            "/api/v1/ai/evaluate",
            headers=HEADERS,
            json={
                "assessmentId": "asm-1",
                "candidateId": "cand-1",
                "assessmentType": "aptitude_and_reasoning",
                "timeTaken": 60,
                "passingScore": 70,
                "questions": [
                    {
                        "questionId": "q1",
                        "stem": "2+2?",
                        "answer": "4",
                        "expectedAnswer": "4",
                        "maxScore": 1,
                    }
                ],
            },
        ).status_code
        == 200
    )
