#!/usr/bin/env python3
"""Stage-5 block lifted-precision figure wrapper.

The actual renderer is packaged beside this wrapper as
``local_precision_pattern_renderer.py`` inside ``code``.
It constructs the lifted variable/factor scopes, expands per-example activation
variables, keeps parameter types distinct, and plots the induced support of

    P = sum_f E_f^T H_f E_f.

This wrapper only supplies notebook-friendly output arguments and compact alias
filenames.
"""

from __future__ import annotations

import shutil
import sys
from pathlib import Path

from supplement_paths import OUT_DIR


PAPER_BLOCK_FILES = {
    "mlp_block_schematic_plus_precision.pdf": "compact_mlp_block_precision.pdf",
    "resnet_block_schematic_plus_precision.pdf": "compact_resnet_block_precision.pdf",
    "transformer_block_schematic_plus_precision.pdf": "compact_transformer_block_precision.pdf",
}


def _compact_source_dir() -> Path:
    return Path(__file__).resolve().parent


def _import_renderer():
    src = _compact_source_dir()
    if str(src) not in sys.path:
        sys.path.insert(0, str(src))
    import local_precision_pattern_renderer as renderer

    return renderer


def generate_block_precision_figures(out_dir: Path = OUT_DIR) -> list[Path]:
    """Generate paper-facing MLP/ResNet/Transformer block precision figures."""

    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    renderer = _import_renderer()
    old_argv = sys.argv[:]
    try:
        sys.argv = [
            "local_precision_pattern_renderer.py",
            "--out_dir",
            str(out_dir),
            "--batch_size_display",
            "3",
            "--max_points",
            "1000000",
        ]
        renderer.main()
    finally:
        sys.argv = old_argv

    written: list[Path] = []
    for paper_name, compact_name in PAPER_BLOCK_FILES.items():
        paper_path = out_dir / paper_name
        compact_path = out_dir / compact_name
        if not paper_path.exists():
            raise FileNotFoundError(f"renderer did not write {paper_path}")
        shutil.copy2(paper_path, compact_path)
        written.extend([paper_path, compact_path])

    overview = out_dir / "lifted_precision_overview.pdf"
    compact_triptych = out_dir / "compact_lifted_precision_triptych.pdf"
    if overview.exists():
        shutil.copy2(overview, compact_triptych)
        written.append(compact_triptych)
    return written


def main() -> None:
    generate_block_precision_figures()


if __name__ == "__main__":
    main()
