"""Tests — case_study + scenario via unified /ai hub (LLM + local fallback)."""

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}

CASE_GEN = {
    "assessment_type": "role_case_play",
    "question_type": "short_answer",
    "assessment_name": "PM Case Play",
    "linked_job": "job-pm-001",
    "duration": 45,
    "difficulty": "moderate",
    "number_of_questions": 2,
    "passing_score": 70,
}
SCENARIO_GEN = {
    "assessment_type": "role_case_play",
    "question_type": "short_answer",
    "assessment_name": "PM Scenarios",
    "linked_job": "job-pm-001",
    "duration": 30,
    "difficulty": "moderate",
    "number_of_questions": 2,
    "passing_score": 70,
}


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


# --- Case studies ---


def test_case_generate_local_fallback() -> None:
    res = client.post("/api/v1/ai/generate", headers=HEADERS, json=CASE_GEN)
    assert res.status_code == 200
    body = res.json()
    assert body["assessment_type"] == "role_case_play"
    assert body["case_id"]
    assert body["title"]
    assert "Product Manager" in (body["scenario_markdown"] or "")
    assert len(body["tasks"]) >= 3
    assert body["rubric"].get("passing_score") == 70
    assert body["passing_score"] == 70


def test_case_generate_uses_llm(monkeypatch: pytest.MonkeyPatch) -> None:
    async def fake_generate_json(*, system, user, local_factory):
        assert "case study" in system.lower()
        return (
            {
                "title": "SaaS churn rescue",
                "scenario_markdown": "## Scenario\nChurn spiked 12%. Propose a plan.",
                "tasks": ["Diagnose drivers", "Prioritize experiments"],
                "rubric": {"structure": 50, "insight": 50, "passing_score": 70},
            },
            False,
            "openai",
        )

    monkeypatch.setattr(
        "app.services.assessments.case_studies.generate_json",
        fake_generate_json,
    )
    res = client.post("/api/v1/ai/generate", headers=HEADERS, json=CASE_GEN)
    assert res.status_code == 200
    body = res.json()
    assert body["assessment_type"] == "role_case_play"
    assert body["title"] == "SaaS churn rescue"
    assert "Churn" in body["scenario_markdown"]
    assert body["tasks"] == ["Diagnose drivers", "Prioritize experiments"]


def test_case_generate_empty_llm_falls_back(monkeypatch: pytest.MonkeyPatch) -> None:
    async def fake_generate_json(*, system, user, local_factory):
        return ({"title": "", "scenario_markdown": ""}, False, "openai")

    monkeypatch.setattr(
        "app.services.assessments.case_studies.generate_json",
        fake_generate_json,
    )
    res = client.post("/api/v1/ai/generate", headers=HEADERS, json=CASE_GEN)
    assert res.status_code == 200
    body = res.json()
    assert body["stub"] is True
    assert body["scenario_markdown"]
    assert body["tasks"]


def test_case_grade_via_evaluate() -> None:
    """role_case_play evaluate uses questions+answers (Platform holds answer key)."""
    res = client.post(
        "/api/v1/ai/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": "case-1",
            "candidateId": "cand-case-1",
            "assessmentType": "role_case_play",
            "timeTaken": 1800,
            "passingScore": 70,
            "questions": [
                {
                    "questionId": "t1",
                    "stem": "Diagnose churn drivers",
                    "answer": "Segment by cohort and product usage",
                    "expectedAnswer": "Segment by cohort and product usage",
                    "maxScore": 1,
                },
                {
                    "questionId": "t2",
                    "stem": "Prioritize experiments",
                    "answer": "Wrong plan",
                    "expectedAnswer": "Run win-back A/B with pricing",
                    "maxScore": 1,
                },
            ],
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["total_score"] == 1.0
    assert body["max_total_score"] == 2.0
    assert body["passed"] is False  # 50% < 70%
    assert body["persisted"] is True
    assert body["candidate_id"] == "cand-case-1"


# --- Scenarios ---


def test_scenario_generate_local_fallback() -> None:
    res = client.post("/api/v1/ai/generate", headers=HEADERS, json=SCENARIO_GEN)
    assert res.status_code == 200
    body = res.json()
    assert body["assessment_type"] == "role_case_play"
    assert body["scenario_set_id"]
    assert len(body["scenarios"]) == 2
    assert body["scenarios"][0]["stem"]


def test_scenario_generate_uses_llm(monkeypatch: pytest.MonkeyPatch) -> None:
    async def fake_generate_json(*, system, user, local_factory):
        assert "scenario" in system.lower()
        return (
            {
                "scenarios": [
                    {
                        "id": "s1",
                        "question_type": "long_answer",
                        "stem": "A key customer threatens churn. What do you do?",
                        "difficulty": "medium",
                    },
                    {
                        "id": "s2",
                        "question_type": "long_answer",
                        "stem": "Engineering capacity is cut 30%. Replan Q3.",
                        "difficulty": "medium",
                    },
                ]
            },
            False,
            "openai",
        )

    monkeypatch.setattr(
        "app.services.assessments.scenarios.generate_json",
        fake_generate_json,
    )
    res = client.post("/api/v1/ai/generate", headers=HEADERS, json=SCENARIO_GEN)
    assert res.status_code == 200
    body = res.json()
    assert body["assessment_type"] == "role_case_play"
    assert "openai" in (body["message"] or "")
    assert len(body["scenarios"]) == 2
    assert "churn" in body["scenarios"][0]["stem"].lower()


def test_scenario_generate_empty_llm_falls_back(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    async def fake_generate_json(*, system, user, local_factory):
        return ({"scenarios": []}, False, "openai")

    monkeypatch.setattr(
        "app.services.assessments.scenarios.generate_json",
        fake_generate_json,
    )
    res = client.post("/api/v1/ai/generate", headers=HEADERS, json=SCENARIO_GEN)
    assert res.status_code == 200
    body = res.json()
    assert body["stub"] is True
    assert len(body["scenarios"]) == 2


def test_scenario_grade_via_evaluate() -> None:
    res = client.post(
        "/api/v1/ai/evaluate",
        headers=HEADERS,
        json={
            "assessmentId": "set-1",
            "candidateId": "cand-scen-1",
            "submissionId": "sub-scen-1",
            "assessmentType": "role_case_play",
            "timeTaken": 900,
            "passingScore": 70,
            "questions": [
                {
                    "questionId": "s1",
                    "stem": "Customer churn threat",
                    "answer": "Talk to customer",
                    "expectedAnswer": "Talk to customer",
                    "maxScore": 1,
                },
                {
                    "questionId": "s2",
                    "stem": "Capacity cut",
                    "answer": "Cut scope",
                    "expectedAnswer": "Cut scope",
                    "maxScore": 1,
                },
            ],
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["total_score"] == 2.0
    assert body["passed"] is True
    assert body["score_percent"] == 100.0
    assert body["persisted"] is True
    assert body["submission_id"] == "sub-scen-1"
