#!/usr/bin/env python3
from __future__ import annotations

import json
import re
import subprocess
from dataclasses import dataclass, asdict
from pathlib import Path

from pypdf import PdfReader


ROOT = Path(__file__).resolve().parent.parent
OUT_DIR = ROOT / "resumes"
INVENTORY_PATH = ROOT / "resume_library_inventory.json"


@dataclass
class SourceDoc:
    path: Path
    kind: str  # "docx" | "pdf"
    output_name: str


@dataclass
class ResumeArtifact:
    source_path: str
    source_type: str
    output_markdown: str
    word_count: int
    line_count: int
    has_education: bool
    has_experience: bool
    has_skills: bool


SOURCES = [
    SourceDoc(ROOT / "2026 Resume Master Doc.docx", "docx", "resume_master_2026.md"),
    SourceDoc(ROOT / "Sample Resume" / "Quillbot_Darsh Shah.pdf", "pdf", "quillbot_darsh_shah.md"),
    SourceDoc(ROOT / "Sample Resume" / "Rippling_Darsh Shah.pdf", "pdf", "rippling_darsh_shah.md"),
    SourceDoc(ROOT / "Sample Resume" / "Snowflake - Darsh Shah.pdf", "pdf", "snowflake_darsh_shah.md"),
]


def extract_docx_text(path: Path) -> str:
    result = subprocess.run(
        ["textutil", "-convert", "txt", "-stdout", str(path)],
        check=True,
        capture_output=True,
        text=True,
    )
    return result.stdout


def extract_pdf_text(path: Path) -> str:
    reader = PdfReader(str(path))
    pages: list[str] = []
    for page in reader.pages:
        pages.append(page.extract_text() or "")
    return "\n\n".join(pages)


def normalize_text(text: str) -> str:
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    text = text.replace("\u2022", "-")
    text = text.replace("\t", " ")
    text = re.sub(r"[ \xa0]+", " ", text)
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip() + "\n"


def wrap_markdown(title: str, source_path: Path, body: str) -> str:
    return (
        f"# {title}\n\n"
        f"_Source: `{source_path.name}`_\n\n"
        f"{body}"
    )


def summarize(markdown_text: str, source: SourceDoc) -> ResumeArtifact:
    lower = markdown_text.lower()
    words = re.findall(r"\b[\w'+.-]+\b", markdown_text)
    return ResumeArtifact(
        source_path=str(source.path.relative_to(ROOT)),
        source_type=source.kind,
        output_markdown=str((OUT_DIR / source.output_name).relative_to(ROOT)),
        word_count=len(words),
        line_count=len(markdown_text.splitlines()),
        has_education="education" in lower,
        has_experience="experience" in lower,
        has_skills="skills" in lower,
    )


def main() -> int:
    OUT_DIR.mkdir(exist_ok=True)
    artifacts: list[ResumeArtifact] = []

    for source in SOURCES:
        if not source.path.exists():
            print(f"Skipping missing source: {source.path}")
            continue

        if source.kind == "docx":
            text = extract_docx_text(source.path)
        elif source.kind == "pdf":
            text = extract_pdf_text(source.path)
        else:
            raise ValueError(f"Unsupported source type: {source.kind}")

        normalized = normalize_text(text)
        title = source.output_name.replace(".md", "").replace("_", " ").title()
        markdown = wrap_markdown(title, source.path, normalized)
        out_path = OUT_DIR / source.output_name
        out_path.write_text(markdown, encoding="utf-8")
        artifacts.append(summarize(markdown, source))
        print(f"Wrote {out_path.relative_to(ROOT)}")

    inventory = {
        "generated_from": "scripts/build_resume_library.py",
        "resume_count": len(artifacts),
        "artifacts": [asdict(a) for a in artifacts],
    }
    INVENTORY_PATH.write_text(json.dumps(inventory, indent=2), encoding="utf-8")
    print(f"Wrote {INVENTORY_PATH.relative_to(ROOT)}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
