"""Shared ResumeService — parse once, reuse versioned profile."""

from __future__ import annotations

import asyncio
import base64
from uuid import uuid4

import pytest
from fastapi.testclient import TestClient

from app.config import get_settings
from app.main import app
from app.services.screening.resume_service import ResumeService

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

RESUME_TXT = (
    "Jane Doe\nBackend Engineer\njane@example.com\n"
    "Skills: Python, FastAPI, PostgreSQL, Redis\n"
    "Experience: Built APIs with FastAPI and Redis caching.\n"
    "Education: B.S. Computer Science\n"
)


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


def test_resolve_reuses_same_content_hash() -> None:
    svc = ResumeService()
    cid = f"cand-resume-reuse-{uuid4().hex[:8]}"

    async def _run():
        first = await svc.resolve(
            candidate_id=cid,
            resume_text=RESUME_TXT,
            persist=True,
        )
        assert first.reused is False
        assert first.resume_version == 1
        assert first.structured.get("name") or first.raw_text

        second = await svc.resolve(
            candidate_id=cid,
            resume_text=RESUME_TXT,
            persist=True,
        )
        assert second.reused is True
        assert second.profile_id == first.profile_id
        assert second.resume_version == first.resume_version

    asyncio.run(_run())


def test_new_resume_text_bumps_version() -> None:
    svc = ResumeService()
    cid = f"cand-resume-ver-{uuid4().hex[:8]}"

    async def _run():
        v1 = await svc.resolve(candidate_id=cid, resume_text=RESUME_TXT, persist=True)
        updated = RESUME_TXT + "\nAdditional: Kubernetes and Docker experience.\n"
        v2 = await svc.resolve(candidate_id=cid, resume_text=updated, persist=True)
        assert v2.reused is False
        assert int(v2.resume_version or 0) > int(v1.resume_version or 0)
        latest = svc.get_profile(cid)
        assert latest is not None
        assert latest.resume_version == v2.resume_version

    asyncio.run(_run())


def test_documents_parse_resume_with_candidate_persists_and_reuses() -> None:
    cid = f"cand-doc-parse-{uuid4().hex[:8]}"
    body = {
        "document_type": "txt",
        "parse_target": "resume",
        "candidate_id": cid,
        "content_base64": base64.b64encode(RESUME_TXT.encode()).decode(),
        "filename": "jane.txt",
    }
    first = client.post("/api/v1/documents/parse", headers=HEADERS, json=body)
    assert first.status_code == 200, first.text
    f = first.json()
    assert f["candidate_id"] == cid
    assert f["resume_profile_id"]
    assert f["resume_reused"] is False
    assert f["structured"]

    second = client.post("/api/v1/documents/parse", headers=HEADERS, json=body)
    assert second.status_code == 200, second.text
    s = second.json()
    assert s["resume_reused"] is True
    assert s["resume_profile_id"] == f["resume_profile_id"]


def test_resume_match_uses_stored_profile_by_candidate_id() -> None:
    cid = f"cand-match-stored-{uuid4().hex[:8]}"
    # Seed profile
    seed = client.post(
        "/api/v1/documents/parse",
        headers=HEADERS,
        json={
            "document_type": "txt",
            "parse_target": "resume",
            "candidate_id": cid,
            "content_base64": base64.b64encode(RESUME_TXT.encode()).decode(),
        },
    )
    assert seed.status_code == 200, seed.text

    res = client.post(
        "/api/v1/resume-match/score",
        headers=HEADERS,
        json={
            "candidate_id": cid,
            "role_title": "Backend Engineer",
            "job_description": (
                "Build APIs in Python/FastAPI, own PostgreSQL schema design, "
                "and operate Redis caches for high-read services."
            ),
            "required_skills": ["Python", "FastAPI", "PostgreSQL"],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["match_score"] is not None
    assert "reused" in (body.get("message") or "").lower() or body["match_score"] >= 0
