"""ResumeInputProcessor — normalize file/text/candidate_id without a second parser."""

from __future__ import annotations

import asyncio
import base64
from io import BytesIO
from uuid import uuid4

import pytest
from fastapi.testclient import TestClient

from app.config import get_settings
from app.errors import GatewayError
from app.main import app
from app.schemas.documents import DocumentType
from app.services.screening.resume_input import ResumeInputProcessor, infer_document_type

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"
)


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


def test_infer_document_type_from_filename() -> None:
    assert infer_document_type(filename="cv.PDF") == DocumentType.PDF
    assert infer_document_type(filename="resume.docx") == DocumentType.DOCX
    assert infer_document_type(filename="old.doc") == DocumentType.DOC
    assert infer_document_type(filename="notes.txt") == DocumentType.TXT


def test_process_plain_text() -> None:
    proc = ResumeInputProcessor()

    async def _run():
        profile = await proc.process(resume_text=RESUME_TXT, require_resume=True)
        assert "Python" in profile.raw_text
        assert profile.source in {"provided_text", "parsed"}

    asyncio.run(_run())


def test_process_missing_resume_raises() -> None:
    proc = ResumeInputProcessor()

    async def _run():
        with pytest.raises(GatewayError) as ei:
            await proc.process(require_resume=True)
        assert ei.value.code == "missing_resume"
        assert ei.value.status_code == 400

    asyncio.run(_run())


def test_process_empty_file_raises() -> None:
    proc = ResumeInputProcessor()

    async def _run():
        with pytest.raises(GatewayError) as ei:
            await proc.process(file_bytes=b"", filename="empty.pdf", require_resume=True)
        assert ei.value.code == "empty_resume"

    asyncio.run(_run())


def test_process_legacy_doc_ole_raises() -> None:
    proc = ResumeInputProcessor()
    # Minimal non-PK bytes pretending to be OLE .doc
    fake_ole = b"\xd0\xcf\x11\xe0" + b"\x00" * 64

    async def _run():
        with pytest.raises(GatewayError) as ei:
            await proc.process(
                file_bytes=fake_ole,
                filename="legacy.doc",
                document_type=DocumentType.DOC,
                require_resume=True,
            )
        assert ei.value.code == "unsupported_document_type"

    asyncio.run(_run())


def test_process_base64_txt_then_job_matching() -> None:
    cid = f"cand-rip-{uuid4().hex[:8]}"
    b64 = base64.b64encode(RESUME_TXT.encode()).decode()
    res = client.post(
        "/api/v1/job-matching/recommend",
        headers=HEADERS,
        json={
            "candidate_id": cid,
            "content_base64": b64,
            "filename": "jane.txt",
            "document_type": "txt",
            "job_catalog": [
                {
                    "job_id": "j1",
                    "title": "Backend Engineer",
                    "skills": ["Python", "FastAPI"],
                }
            ],
        },
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["catalog_size"] == 1
    assert body["recommendations"]
    assert "j1" in {r["job_id"] for r in body["recommendations"]}


def test_documents_parse_file_multipart() -> None:
    cid = f"cand-multipart-{uuid4().hex[:8]}"
    files = {
        "file": ("jane.txt", BytesIO(RESUME_TXT.encode()), "text/plain"),
    }
    data = {
        "parse_target": "resume",
        "candidate_id": cid,
        "document_type": "txt",
        "language": "en",
    }
    res = client.post(
        "/api/v1/documents/parse-file",
        headers=HEADERS,
        files=files,
        data=data,
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["candidate_id"] == cid
    assert "raw_text" not in body
    assert "blocks" not in body
    assert "structured" not in body
    assert body["personal"]["name"] or body["skills"]
    assert "Python" in (body.get("skills") or []) or "Python" in str(body)
    assert body["resume_profile_id"]


def test_resume_match_accepts_content_base64() -> None:
    b64 = base64.b64encode(RESUME_TXT.encode()).decode()
    res = client.post(
        "/api/v1/resume-match/score",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "job_description": (
                "We need a Backend Engineer with Python and FastAPI experience "
                "building production APIs."
            ),
            "content_base64": b64,
            "filename": "jane.txt",
            "document_type": "txt",
            "required_skills": ["Python", "FastAPI"],
        },
    )
    assert res.status_code == 200, res.text
    assert res.json()["match_score"] is not None
