#!/usr/bin/env python3
"""Smoke-test live resume-dependent APIs with sample_resumes/Resume-1.pdf.

Usage (server running on :8000):
  python scripts/smoke_resume_apis.py
"""

from __future__ import annotations

import base64
import json
import sys
from pathlib import Path
from uuid import uuid4

import httpx

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from app.config import get_settings  # noqa: E402

BASE = "http://127.0.0.1:8000/api/v1"
PDF_PATH = ROOT / "sample_resumes" / "Resume-1.pdf"
PDF_URL = (
    "https://raw.githubusercontent.com/Codex-Amit/Resume-parser/main/"
    "sample_resumes/Resume-1.pdf"
)
JD = (
    "We are hiring a Substitute Teacher / Educator for high school classrooms. "
    "Must manage classrooms of 20+ students, follow lesson plans, communicate "
    "with teachers, and adapt across multiple subject areas. Chicago IL."
)


def main() -> int:
    if not PDF_PATH.is_file():
        print(f"Missing {PDF_PATH} — download demo Resume-1.pdf first")
        return 2

    token = get_settings().internal_api_token
    headers = {"X-Internal-Token": token}
    pdf_b64 = base64.b64encode(PDF_PATH.read_bytes()).decode()
    cid = f"cand-demo-resume-{uuid4().hex[:8]}"
    results: list[tuple[str, int]] = []

    def record(name: str, res: httpx.Response) -> None:
        ok = 200 <= res.status_code < 300
        brief = ""
        try:
            body = res.json()
            if isinstance(body, dict):
                keep = {
                    k: body[k]
                    for k in (
                        "status",
                        "message",
                        "resume_reused",
                        "match_score",
                        "catalog_size",
                    )
                    if k in body
                }
                brief = json.dumps(keep, default=str)[:180]
        except Exception:
            brief = (res.text or "")[:120]
        print(f"[{'PASS' if ok else 'FAIL'}] {name} → {res.status_code} {brief}")
        results.append((name, res.status_code))

    with httpx.Client(timeout=120.0) as client:
        r = client.post(
            f"{BASE}/documents/parse",
            headers=headers,
            json={
                "document_type": "pdf",
                "parse_target": "resume",
                "candidate_id": cid,
                "content_base64": pdf_b64,
                "filename": "Resume-1.pdf",
            },
        )
        record("POST /documents/parse", r)

        r = client.post(
            f"{BASE}/documents/parse",
            headers=headers,
            json={
                "document_type": "pdf",
                "parse_target": "resume",
                "candidate_id": cid,
                "content_base64": pdf_b64,
                "filename": "Resume-1.pdf",
            },
        )
        record("POST /documents/parse (reuse)", r)

        with PDF_PATH.open("rb") as fh:
            r = client.post(
                f"{BASE}/documents/parse-file",
                headers=headers,
                files={"file": ("Resume-1.pdf", fh, "application/pdf")},
                data={
                    "parse_target": "resume",
                    "candidate_id": f"{cid}-mp",
                    "document_type": "pdf",
                },
            )
        record("POST /documents/parse-file (structured only)", r)
        if r.status_code == 200:
            lean = r.json()
            assert "raw_text" not in lean and "personal" in lean

        r = client.post(
            f"{BASE}/documents/parse",
            headers=headers,
            json={
                "document_type": "pdf",
                "parse_target": "resume",
                "candidate_id": f"{cid}-url",
                "source_url": PDF_URL,
                "filename": "Resume-1.pdf",
            },
        )
        record("POST /documents/parse (source_url)", r)

        r = client.get(
            f"{BASE}/documents/resume-profile",
            headers=headers,
            params={"candidate_id": cid},
        )
        record("GET /documents/resume-profile", r)

        r = client.post(
            f"{BASE}/resume-match/score",
            headers=headers,
            json={
                "candidate_id": cid,
                "role_title": "Substitute Teacher",
                "job_description": JD,
                "required_skills": ["classroom management", "lesson plans"],
            },
        )
        record("POST /resume-match/score (candidate_id)", r)

        r = client.post(
            f"{BASE}/resume-match/score",
            headers=headers,
            json={
                "role_title": "Substitute Teacher",
                "job_description": JD,
                "content_base64": pdf_b64,
                "filename": "Resume-1.pdf",
                "document_type": "pdf",
            },
        )
        record("POST /resume-match/score (PDF)", r)

        r = client.post(
            f"{BASE}/job-matching/recommend",
            headers=headers,
            json={
                "candidate_id": cid,
                "content_base64": pdf_b64,
                "filename": "Resume-1.pdf",
                "document_type": "pdf",
                "job_catalog": [
                    {
                        "job_id": "job-sub-001",
                        "title": "Substitute Teacher",
                        "skills": ["classroom management", "teaching"],
                    },
                    {
                        "job_id": "job-be-999",
                        "title": "Backend Engineer",
                        "skills": ["Python", "FastAPI"],
                    },
                ],
            },
        )
        record("POST /job-matching/recommend", r)

        r = client.post(
            f"{BASE}/prep-plans/generate",
            headers=headers,
            json={
                "candidate_id": cid,
                "role_title": "Substitute Teacher",
                "job_description": JD,
                "content_base64": pdf_b64,
                "filename": "Resume-1.pdf",
                "document_type": "pdf",
            },
        )
        record("POST /prep-plans/generate", r)

        r = client.post(
            f"{BASE}/interview-workflows",
            headers=headers,
            json={
                "roleTitle": "Substitute Teacher",
                "title": "Demo sub teacher interview",
                "jobDescription": JD,
                "mode": "text",
                "durationMinutes": 30,
                "skills": ["classroom management"],
                "language": "en",
            },
        )
        record("POST /interview-workflows", r)
        wid = None
        if r.status_code == 200:
            body = r.json()
            wid = body.get("workflowId") or body.get("workflow_id") or body.get("id")

        if wid:
            pr = client.get(f"{BASE}/personas", headers=headers)
            persona_id = "technical"
            if pr.status_code == 200:
                data = pr.json()
                items = data if isinstance(data, list) else data.get("personas") or []
                if items:
                    persona_id = items[0].get("persona_id") or items[0].get("id") or persona_id
            r = client.post(
                f"{BASE}/interview-workflows/{wid}/questions/generate",
                headers=headers,
                json={
                    "personaId": persona_id,
                    "questionCount": 3,
                    "questionTypes": ["behavioral", "scenario"],
                    "replaceExisting": True,
                    "candidateId": cid,
                    "contentBase64": pdf_b64,
                    "filename": "Resume-1.pdf",
                    "documentType": "pdf",
                },
            )
            record("POST .../questions/generate", r)

    fails = [n for n, c in results if not (200 <= c < 300)]
    print(f"\ncandidate_id={cid} total={len(results)} fail={len(fails)}")
    return 1 if fails else 0


if __name__ == "__main__":
    raise SystemExit(main())
