"""
build_resume_from_json.py — Render a tailored DOCX from a per-job JSON.

This is the active tailoring generator path (since at least SmartAsset and
TonyRole submissions, 2026-07). The legacy `scripts/resume_generator.py` and
the locked `scripts/resume_template.py` (JOBS tuples) are no longer the
working approach — per-job JSONs have won on every recent submission.

JSON shape (see Pantheon_Sr-Manager-RevOps-Marketing.json for a working example):
{
  "title": "Senior Marketing Operations Manager | Funnel & Revenue Operations Strategy",
  "summary": "4-5 sentences. Pull JD language verbatim where honest.",
  "competencies": [
    {"label": "Label:  ", "items": "tools | and | skills"},
    ...
  ],
  "experience": [
    {
      "header": "Title | Company | Location | Dates",
      "bullets": ["•", "•", "•"]
    },
    ...
  ],
  "education": ["line 1", "line 2"],
  "military_note": "Special Forces Medical Sergeant (MOS 18D), E-5, Honorable Discharge"
}

Usage:
    python scripts/build_resume_from_json.py \\
        --json /root/.hermes/staging/<job>/<Company>_<Title>.json \\
        --out /root/.hermes/outbox/Rob_Blake_Resume_<Company>_<Title>.docx

If --out is omitted, defaults to /root/.hermes/outbox/Rob_Blake_Resume_<Company>_<Title>.docx
where Company and Title are parsed from the JSON `title` field (slugified).

Style matches the locked template: navy/Calibri, 11pt body, 20pt name header,
margins 1.5cm top/bottom, 1.8cm left/right.

History:
    2026-07-23  carved out from /root/.hermes/staging/job1_2025-07-23_pantheon/
                build_pantheon_resume.py after the Pantheon tailoring session
                verified the JSON-in → DOCX-out path is the working pattern.
"""

import argparse
import json
import os
import re

from docx import Document
from docx.shared import Pt, RGBColor, Inches, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH

NAVY = RGBColor(0x1F, 0x38, 0x64)
BLACK = RGBColor(0x00, 0x00, 0x00)
DARK = RGBColor(0x33, 0x33, 0x36)

NAME = "ROB BLAKE"
CONTACT = "Phone: 303-800-7628  •  rkblake@gmail.com  •  LinkedIn.com/in/robkblake"


def set_run(para, text, bold=False, pt=11, color=BLACK, font="Calibri"):
    run = para.add_run(text)
    run.bold = bold
    run.font.size = Pt(pt)
    run.font.color.rgb = color
    run.font.name = font
    return run


def center_para(doc, space_after=0):
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.paragraph_format.space_before = Pt(0)
    p.paragraph_format.space_after = Pt(space_after)
    return p


def section_heading(doc, text):
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.LEFT
    p.paragraph_format.space_before = Pt(10)
    p.paragraph_format.space_after = Pt(2)
    set_run(p, text, bold=True, pt=11, color=NAVY)
    return p


def body(doc, text, space_before=0, space_after=3):
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.LEFT
    p.paragraph_format.space_before = Pt(space_before)
    p.paragraph_format.space_after = Pt(space_after)
    p.paragraph_format.line_spacing = Pt(13)
    set_run(p, text, bold=False, pt=11, color=DARK)
    return p


def role_line(doc, title, dates, company, location=None):
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.LEFT
    p.paragraph_format.space_before = Pt(8)
    p.paragraph_format.space_after = Pt(0)
    p.paragraph_format.keep_with_next = True
    set_run(p, title, bold=True, pt=11, color=DARK)
    set_run(p, "\t" + dates, bold=False, pt=11, color=DARK)
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.LEFT
    p.paragraph_format.space_before = Pt(0)
    p.paragraph_format.space_after = Pt(1)
    p.paragraph_format.keep_with_next = True
    if location:
        set_run(p, company + " — " + location, bold=False, pt=11, color=NAVY)
    else:
        set_run(p, company, bold=False, pt=11, color=NAVY)
    return p


def bullet(doc, text):
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.LEFT
    p.paragraph_format.space_before = Pt(0)
    p.paragraph_format.space_after = Pt(3)
    p.paragraph_format.line_spacing = Pt(13)
    p.paragraph_format.left_indent = Inches(0.25)
    set_run(p, "•  " + text, bold=False, pt=11, color=DARK)
    return p


def competency(doc, label, rest):
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.LEFT
    p.paragraph_format.space_before = Pt(0)
    p.paragraph_format.space_after = Pt(3)
    set_run(p, label, bold=True, pt=11, color=DARK)
    set_run(p, rest, bold=False, pt=11, color=DARK)
    return p


def slugify(s):
    s = re.sub(r"[^a-zA-Z0-9]+", "-", s).strip("-")
    return s


def parse_header(header):
    parts = [s.strip() for s in header.split("|")]
    if len(parts) == 4:
        # JSON headers use: Title | Company | Location | Dates.
        # role_line() expects dates before location.
        return parts[0], parts[1], parts[3], parts[2], None
    if len(parts) == 3:
        return parts[0], parts[1], parts[2], None, None
    return parts[0], "", "", None, None


def build_resume(json_path, out_path=None):
    with open(json_path) as f:
        data = json.load(f)

    if not out_path:
        first = data["experience"][0]["header"]
        title, company, _, _, _ = parse_header(first)
        company_slug = company.split(",")[0].split("|")[0].strip()
        title_slug = title.split(",")[0].split("|")[0].strip()
        out_path = (
            f"/root/.hermes/outbox/Rob_Blake_Resume_"
            f"{slugify(company_slug)}_{slugify(title_slug)}.docx"
        )

    doc = Document()
    section = doc.sections[0]
    section.top_margin = Cm(1.5)
    section.bottom_margin = Cm(1.5)
    section.left_margin = Cm(1.8)
    section.right_margin = Cm(1.8)

    p = center_para(doc)
    set_run(p, NAME, bold=True, pt=20, color=NAVY)
    p = center_para(doc, space_after=2)
    set_run(p, data["title"], bold=True, pt=12, color=BLACK)
    p = center_para(doc, space_after=12)
    set_run(p, CONTACT, bold=False, pt=10, color=BLACK)

    section_heading(doc, "PROFESSIONAL SUMMARY")
    body(doc, data["summary"], space_after=6)

    section_heading(doc, "CORE COMPETENCIES")
    for comp in data["competencies"]:
        competency(doc, comp["label"] + "  ", comp["items"])

    section_heading(doc, "EXPERIENCE")
    for job in data["experience"]:
        title, company, dates, location, _ = parse_header(job["header"])
        role_line(doc, title, dates, company, location)
        for b in job["bullets"]:
            bullet(doc, b)

    section_heading(doc, "EDUCATION")
    for line in data["education"]:
        body(doc, line, space_after=3)

    section_heading(doc, "MILITARY")
    body(doc, data["military_note"], space_after=6)

    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    doc.save(out_path)
    print("Saved:", out_path)
    print("Size:", os.path.getsize(out_path), "bytes")
    return out_path


def main():
    parser = argparse.ArgumentParser(description="Render tailored DOCX from per-job JSON.")
    parser.add_argument("--json", required=True, help="Path to tailored JSON")
    parser.add_argument("--out", help="Output DOCX path (default: /root/.hermes/outbox/Rob_Blake_Resume_<Company>_<Title>.docx)")
    args = parser.parse_args()
    build_resume(args.json, args.out)


if __name__ == "__main__":
    main()
