"""Tests — POST /resume-match/score LLM path + 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}

PAYLOAD = {
    "role_title": "Backend Engineer",
    "job_description": "Need Python FastAPI and PostgreSQL experience for APIs.",
    "resume_text": "Built FastAPI services with Python for 3 years.",
    "required_skills": ["Python", "FastAPI", "Kubernetes"],
}


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


def test_resume_match_local_fallback() -> None:
    res = client.post("/api/v1/resume-match/score", headers=HEADERS, json=PAYLOAD)
    assert res.status_code == 200
    body = res.json()
    assert body["status"] == "succeeded"
    assert body["stub"] is True
    assert body["message"].startswith("Resume match via local")
    assert 0.0 <= body["match_score"] <= 1.0
    assert "Python" in body["matched_skills"]
    assert "FastAPI" in body["matched_skills"]
    assert "Kubernetes" in body["missing_skills"]
    assert body["screen_passed"] is True
    assert body["summary"]


def test_resume_match_uses_llm_when_available(monkeypatch: pytest.MonkeyPatch) -> None:
    async def fake_generate_json(*, system, user, local_factory):
        assert "resume screening" in system.lower()
        assert "Backend Engineer" in user
        return (
            {
                "match_score": 0.82,
                "matched_skills": ["Python", "FastAPI", "PostgreSQL"],
                "missing_skills": ["Kubernetes"],
                "summary": "Strong backend fit; Kubernetes not evidenced.",
            },
            False,
            "openai",
        )

    monkeypatch.setattr(
        "app.services.screening.resume_match.generate_json",
        fake_generate_json,
    )
    res = client.post("/api/v1/resume-match/score", headers=HEADERS, json=PAYLOAD)
    assert res.status_code == 200
    body = res.json()
    assert body["stub"] is False
    assert body["message"] == "Resume match via openai"
    assert body["match_score"] == 0.82
    assert body["matched_skills"] == ["Python", "FastAPI", "PostgreSQL"]
    assert body["missing_skills"] == ["Kubernetes"]
    assert body["screen_passed"] is True
    assert "Kubernetes" in body["summary"]


def test_resume_match_llm_incomplete_fills_from_local(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    async def fake_generate_json(*, system, user, local_factory):
        return ({"summary": "Partial model output"}, False, "openai")

    monkeypatch.setattr(
        "app.services.screening.resume_match.generate_json",
        fake_generate_json,
    )
    res = client.post("/api/v1/resume-match/score", headers=HEADERS, json=PAYLOAD)
    assert res.status_code == 200
    body = res.json()
    assert body["stub"] is False
    assert "Python" in body["matched_skills"]
    assert "Kubernetes" in body["missing_skills"]
    assert body["summary"] == "Partial model output"
    assert 0.0 <= body["match_score"] <= 1.0


def test_resume_match_clamps_out_of_range_score(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    async def fake_generate_json(*, system, user, local_factory):
        return (
            {
                "match_score": 1.7,
                "matched_skills": ["Python"],
                "missing_skills": ["Kubernetes"],
                "summary": "Overconfident score",
            },
            False,
            "openai",
        )

    monkeypatch.setattr(
        "app.services.screening.resume_match.generate_json",
        fake_generate_json,
    )
    res = client.post("/api/v1/resume-match/score", headers=HEADERS, json=PAYLOAD)
    assert res.status_code == 200
    assert res.json()["match_score"] == 1.0
    assert res.json()["screen_passed"] is True
