"""Build the manuscript PDF with the installed TeX toolchain; no downloads."""
from __future__ import annotations

import argparse
import hashlib
import json
import shutil
import subprocess
import time
from datetime import datetime, timezone
from pathlib import Path


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--work-dir", type=Path, required=True,
                        help="Existing empty build directory, outside the source tree")
    parser.add_argument("--receipt", type=Path, required=True,
                        help="New JSON receipt path (parent must exist)")
    args = parser.parse_args()
    root = Path(__file__).resolve().parent
    work = args.work_dir.resolve(strict=True)
    receipt = args.receipt.resolve()
    if any(work.iterdir()) or receipt.exists() or not receipt.parent.is_dir():
        raise SystemExit("Use an empty build directory and a new receipt in an existing directory")
    tex = shutil.which("pdflatex")
    if not tex:
        raise SystemExit("pdflatex is required; no automatic installation is attempted")
    job = "symmetry_signatures_and_circuit_partitions"
    command = [tex, "--disable-installer", "-interaction=nonstopmode",
               "-halt-on-error", "-file-line-error", f"-jobname={job}",
               f"-output-directory={work}", "main.tex"]
    record = {"schema": "heritage.symmetry-signatures.pdf-build.v1",
              "started_at_utc": datetime.now(timezone.utc).isoformat(),
              "source_sha256": sha(root / "main.tex"),
              "figure_sha256": {p.name: sha(p) for p in sorted((root / "figures").glob("*.pdf"))},
              "cwd": str(root), "command": command, "passes": [], "status": "FAIL"}
    for number in (1, 2):
        started = time.perf_counter()
        result = subprocess.run(command, cwd=root, capture_output=True, timeout=60)
        output = result.stdout.decode("utf-8", "replace")
        error = result.stderr.decode("utf-8", "replace")
        record["passes"].append({"pass": number, "returncode": result.returncode,
                                 "seconds": round(time.perf_counter() - started, 3),
                                 "stdout": output, "stderr": error})
        if result.returncode:
            receipt.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
            raise SystemExit(f"TeX failed in pass {number}; see {receipt}")
    log = (work / f"{job}.log").read_text(encoding="utf-8", errors="replace")
    record["layout_messages"] = [line for line in log.splitlines()
                                  if any(s in line for s in ("Overfull", "Underfull", "Warning", "undefined"))]
    pdf = work / f"{job}.pdf"
    record.update(status="PASS", pdf_sha256=sha(pdf), pdf_bytes=pdf.stat().st_size,
                  pdf_path=str(pdf), finished_at_utc=datetime.now(timezone.utc).isoformat())
    receipt.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({k: record[k] for k in ("status", "pdf_sha256", "pdf_bytes", "layout_messages")}, ensure_ascii=False))


if __name__ == "__main__":
    main()
