"""Unified reference-check API — questionnaire → response → report."""

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.reports.reference_check_store import get_reference_check_store

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


@pytest.fixture(autouse=True)
def _force_local(monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setattr("app.llm._provider_available", lambda _name: False)
    # Fresh store per test
    store = get_reference_check_store()
    store._by_id.clear()


def test_legacy_paths_removed() -> None:
    assert (
        client.post(
            "/api/v1/reference-checks/questionnaire",
            headers=HEADERS,
            json={"candidate_id": "c1", "role_title": "Eng"},
        ).status_code
        == 404
    )
    assert (
        client.post(
            "/api/v1/reference-checks/report",
            headers=HEADERS,
            json={
                "candidate_id": "c1",
                "role_title": "Eng",
                "referee_responses": [{"answers": {"a": "b"}}],
            },
        ).status_code
        == 404
    )


def test_generate_questionnaire() -> None:
    res = client.post(
        "/api/v1/reference-checks?action=generate_questionnaire",
        headers=HEADERS,
        json={
            "candidate_id": "cand-1",
            "candidate_name": "Jane Doe",
            "role_title": "Backend Engineer",
            "referees": [
                {"name": "Alex Manager", "relationship": "manager"},
            ],
            "count": 5,
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["action"] == "generate_questionnaire"
    assert body["questionnaire_id"]
    assert body["reference_check_id"] == body["questionnaire_id"]
    assert len(body["questions"]) == 5
    assert body["check_status"] == "awaiting_responses"
    assert body["referees"]


def test_full_flow_reuses_responses_for_report() -> None:
    q = client.post(
        "/api/v1/reference-checks",
        headers=HEADERS,
        json={
            "action": "generate_questionnaire",
            "candidate_id": "cand-flow",
            "role_title": "Backend Engineer",
            "count": 4,
            "referees": [{"name": "Alex Manager", "relationship": "manager"}],
        },
    ).json()
    check_id = q["reference_check_id"]
    qids = [x["id"] for x in q["questions"]]

    sub = client.post(
        "/api/v1/reference-checks?action=submit_response",
        headers=HEADERS,
        json={
            "candidate_id": "cand-flow",
            "reference_check_id": check_id,
            "referee": {"name": "Alex Manager", "relationship": "manager"},
            "response": {
                "answers": {qid: f"Answer for {qid}" for qid in qids},
            },
        },
    )
    assert sub.status_code == 200, sub.text
    body = sub.json()
    assert body["response_id"]
    assert body["incomplete_question_ids"] == []
    assert body["responses_received"] == 1
    assert body["check_status"] in {"completed", "partial", "awaiting_responses"}

    report = client.post(
        "/api/v1/reference-checks?action=generate_report",
        headers=HEADERS,
        json={
            "candidate_id": "cand-flow",
            "reference_check_id": check_id,
            "role_title": "Backend Engineer",
        },
    )
    assert report.status_code == 200, report.text
    rbody = report.json()
    assert rbody["report_id"]
    assert rbody["sentiment_summary"]
    assert rbody["strengths"]
    assert rbody["report_markdown"]
    assert rbody["check_status"] == "report_ready"

    # Second report call reuses cached report (no duplicate LLM work)
    again = client.post(
        "/api/v1/reference-checks?action=generate_report",
        headers=HEADERS,
        json={
            "candidate_id": "cand-flow",
            "reference_check_id": check_id,
        },
    ).json()
    assert again["report_id"] == rbody["report_id"]
    assert "reused" in again["message"].lower()


def test_incomplete_response_tracked() -> None:
    q = client.post(
        "/api/v1/reference-checks?action=generate_questionnaire",
        headers=HEADERS,
        json={
            "candidate_id": "cand-inc",
            "role_title": "Engineer",
            "count": 4,
        },
    ).json()
    check_id = q["reference_check_id"]
    first_qid = q["questions"][0]["id"]

    res = client.post(
        "/api/v1/reference-checks?action=submit_response",
        headers=HEADERS,
        json={
            "candidate_id": "cand-inc",
            "reference_check_id": check_id,
            "referee": {"name": "Sam Peer"},
            "response": {"answers": {first_qid: "Only one answer"}},
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["incomplete_question_ids"]
    assert body["errors"]
    assert body["check_status"] == "partial"


def test_report_with_inline_responses_bc() -> None:
    res = client.post(
        "/api/v1/reference-checks?action=generate_report",
        headers=HEADERS,
        json={
            "candidate_id": "cand-inline",
            "role_title": "Backend Engineer",
            "referee_responses": [
                {
                    "referee_name": "Alex Manager",
                    "relationship": "former manager",
                    "answers": {"reliability": "high", "teamwork": "excellent"},
                }
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["report_id"]
    assert body["recommendation"]


def test_missing_action_422() -> None:
    res = client.post(
        "/api/v1/reference-checks",
        headers=HEADERS,
        json={"candidate_id": "cand-1", "role_title": "Eng"},
    )
    assert res.status_code == 422
