"""Unified text/voice/video final-evaluation + deterministic PDF."""

from __future__ import annotations

from types import SimpleNamespace

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}


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


def test_text_eval_persists_and_pdf_is_deterministic() -> None:
    interview_id = "ue-text-1"
    candidate_id = "cand-ue-text-1"
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": interview_id,
            "candidate_id": candidate_id,
            "interview_mode": "text",
            "role_title": "Backend Engineer",
            "job_description": "Build FastAPI services.",
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "Describe FastAPI experience.",
                    "answer": "I ship FastAPI APIs with Postgres and clear ownership.",
                }
            ],
            "turn_scores": [
                {"question_id": "q-1", "score": 0.88, "provenance": "supplied"}
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["evaluation_status"] == "completed"
    assert body["evaluation_id"]
    assert body["overall_score"] == pytest.approx(0.88)

    status = client.get(
        "/api/v1/interviews/final-evaluation/status",
        headers=HEADERS,
        params={"candidate_id": candidate_id, "interview_id": interview_id},
    )
    assert status.status_code == 200
    assert status.json()["evaluation_status"] == "completed"
    assert status.json()["overall_score"] == pytest.approx(0.88)

    pdf = client.post(
        "/api/v1/reports/evaluation-pdf",
        headers=HEADERS,
        json={"candidate_id": candidate_id, "interview_id": interview_id},
    )
    assert pdf.status_code == 200, pdf.text
    body_pdf = pdf.json()
    md = body_pdf["summary_markdown"]
    assert "0.88" in md or "0.880" in md
    assert "Text Interview Evaluation" in md
    assert "not recalculated" in md.lower()
    report = body_pdf["report"]
    assert report["report_title"] == "Text Interview Evaluation"
    assert report["candidate_interview"]["candidate_id"] == candidate_id
    assert report["overall"]["overall_score"] == pytest.approx(0.88)
    assert "question_evaluations" in report
    assert "key_strengths" in report
    assert "areas_of_improvement" in report
    assert report["final_recommendation"]["note"]
    assert body_pdf["pdf_base64"]
    assert body_pdf["download_url"]


def test_voice_one_audio_per_question(monkeypatch: pytest.MonkeyPatch) -> None:
    """Q1 audio + Q2 audio — exactly one file each, transcribed separately."""
    from app.schemas.transcription import TranscriptionProvider, TranscriptionResponse
    from app.schemas.common import JobStatus

    calls: list[str | None] = []

    async def fake_transcribe(self, payload):
        calls.append(payload.source_url)
        n = len(calls)
        return TranscriptionResponse(
            status=JobStatus.SUCCEEDED,
            stub=True,
            message="mock",
            text=f"Answer for question {n} about Redis and SQL.",
            provider=TranscriptionProvider.STUB,
            model="mock",
        )

    monkeypatch.setattr(
        "app.services.voice.transcription.TranscriptionService.transcribe",
        fake_transcribe,
    )

    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": "ue-voice-multi",
            "candidate_id": "cand-ue-voice-multi",
            "interview_mode": "voice",
            "role_title": "Backend Engineer",
            "job_description": "Build APIs.",
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "How do you cache?",
                    "audio_source_url": "https://example.com/q1.wav",
                },
                {
                    "question_id": "q-2",
                    "question": "How do you index SQL?",
                    "audio_source_url": "https://example.com/q2.wav",
                },
            ],
            "turn_scores": [
                {"question_id": "q-1", "score": 0.7, "provenance": "supplied"},
                {"question_id": "q-2", "score": 0.6, "provenance": "supplied"},
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["evaluation_status"] == "completed"
    assert len(calls) == 2
    by_qid = {q["question_id"]: q for q in body["questions"]}
    assert "question 1" in (by_qid["q-1"]["answer"] or "")
    assert "question 2" in (by_qid["q-2"]["answer"] or "")


def test_voice_eval_uses_transcription(monkeypatch: pytest.MonkeyPatch) -> None:
    from app.schemas.transcription import TranscriptionResponse
    from app.schemas.common import JobStatus

    async def fake_transcribe(self, payload):
        from app.schemas.transcription import TranscriptionProvider

        return TranscriptionResponse(
            status=JobStatus.SUCCEEDED,
            stub=True,
            message="mock",
            text="I designed Redis caching with TTLs and invalidation.",
            provider=TranscriptionProvider.STUB,
            model="mock",
        )

    monkeypatch.setattr(
        "app.services.voice.transcription.TranscriptionService.transcribe",
        fake_transcribe,
    )

    interview_id = "ue-voice-1"
    candidate_id = "cand-ue-voice-1"
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": interview_id,
            "candidate_id": candidate_id,
            "interview_mode": "voice",
            "role_title": "Backend Engineer",
            "job_description": "Build APIs.",
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "How do you cache?",
                    "audio_base64": "AAAA",
                }
            ],
            "turn_scores": [
                {"question_id": "q-1", "score": 0.7, "provenance": "supplied"}
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["evaluation_status"] == "completed"
    assert "Redis" in (body["questions"][0]["answer"] or "")


def test_voice_stt_failure_marks_failed_not_pdf(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    async def boom(self, payload):
        raise RuntimeError("STT down")

    monkeypatch.setattr(
        "app.services.voice.transcription.TranscriptionService.transcribe",
        boom,
    )
    interview_id = "ue-voice-fail"
    candidate_id = "cand-ue-voice-fail"
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": interview_id,
            "candidate_id": candidate_id,
            "interview_mode": "voice",
            "role_title": "Backend Engineer",
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "Tell me about yourself",
                    "audio_base64": "AAAA",
                }
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["evaluation_status"] == "failed"
    assert body["error_code"] == "transcription_failed"

    pdf = client.post(
        "/api/v1/reports/evaluation-pdf",
        headers=HEADERS,
        json={"candidate_id": candidate_id, "interview_id": interview_id},
    )
    assert pdf.status_code == 409


def test_video_eval_uses_vi_transcript_not_emotion(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    async def fake_analyze(self, payload):
        return SimpleNamespace(
            faces_detected_ratio=0.9,
            multi_face_frames=0,
            visual_events=[],
            transcript=SimpleNamespace(
                text="I own PostgreSQL schema migrations and indexes."
            ),
            report=SimpleNamespace(
                summary="Candidate present",
                limitations=["No emotion scoring"],
            ),
        )

    monkeypatch.setattr(
        "app.services.video.intelligence.VideoIntelligenceService.analyze",
        fake_analyze,
    )

    interview_id = "ue-video-1"
    candidate_id = "cand-ue-video-1"
    res = client.post(
        "/api/v1/interviews/final-evaluation",
        headers=HEADERS,
        json={
            "interview_id": interview_id,
            "candidate_id": candidate_id,
            "interview_mode": "video",
            "consent_given": True,
            "role_title": "Backend Engineer",
            "job_description": "Build data services.",
            "qa_items": [
                {
                    "question_id": "q-1",
                    "question": "How do you design schemas?",
                    "video_base64": "AAAA",
                }
            ],
            "turn_scores": [
                {"question_id": "q-1", "score": 0.8, "provenance": "supplied"}
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["evaluation_status"] == "completed"
    assert "PostgreSQL" in (body["questions"][0]["answer"] or "")
    assert any("not facial" in w.lower() or "observational" in w.lower() for w in body["warnings"])
