"""Re-emit sip_view.svg in an academic palette (white background, black
strokes) and convert it to PDF for the 1H-codesign-paper Figure 1.

Source of truth: docs/diagrams/sip_view.svg (generated by
src/kernbench/topology/visualizer.py, dark-ish theme).

Treatment per user request: keep the layout intact, just force a white
canvas and turn every stroke black; promote faint label text to black so
all annotations stay legible on white.
"""
from __future__ import annotations

import re
import shutil
import subprocess
from pathlib import Path

REPO = Path(__file__).resolve().parents[2]
SRC_SVG = REPO / "docs" / "diagrams" / "sip_view.svg"
OUT_DIR = REPO / "docs" / "report" / "1H-codesign-paper" / "figures"
OUT_SVG = OUT_DIR / "sip_architecture.svg"
OUT_PDF = OUT_DIR / "sip_architecture.pdf"

# Drop the "SIP VIEW" title; the figure caption already names the level.
TITLE_REMOVE: list[tuple[str, str]] = [
    ('  <text x="324" y="18" text-anchor="middle" font-family="monospace" '
     'font-size="14" font-weight="bold" fill="#1e293b">SIP VIEW</text>\n',
     ''),
]

COLOR_MAP: list[tuple[str, str]] = [
    # canvas background slate-50 -> pure white
    ('fill="#f8fafc"', 'fill="#ffffff"'),
    # all strokes -> black
    ('stroke="#3b82f6"', 'stroke="#000000"'),  # UCIe mesh blue lines
    ('stroke="#475569"', 'stroke="#000000"'),  # cube block borders
    ('stroke="#0ea5e9"', 'stroke="#000000"'),  # I/O sky-blue lines
    # link annotation text slate-500 -> black for readability
    ('fill="#64748b"', 'fill="#000000"'),
]

# Font-size bumps so labels survive LaTeX \linewidth scaling at the
# half-text-width subfigure. CUBE block labels overflow the 48px block
# rects, which is acceptable here.
FONT_MAP: dict[str, str] = {
    "7":  "10",
    "14": "17",
}

# Tighten whitespace: cube grid occupies x=[84,564], y=[128,520]; IO
# chiplet sits around y~50. With the title removed, crop top to y=40 so
# the IO chiplet keeps a small headroom. Crop 70px on each side and 113
# px from bottom.
LAYOUT_FIXUP: list[tuple[str, str]] = [
    ('<svg xmlns="http://www.w3.org/2000/svg" width="648" height="648" '
     'viewBox="0 0 648 648">',
     '<svg xmlns="http://www.w3.org/2000/svg" width="508" height="495" '
     'viewBox="70 40 508 495">'),
]


def _bump_font(m: re.Match) -> str:
    return f'font-size="{FONT_MAP.get(m.group(1), m.group(1))}"'


def main() -> None:
    if not SRC_SVG.exists():
        raise SystemExit(f"source SVG missing: {SRC_SVG}")
    rsvg = shutil.which("rsvg-convert")
    if rsvg is None:
        raise SystemExit("rsvg-convert not found (brew install librsvg)")

    svg = SRC_SVG.read_text(encoding="utf-8")
    for old, new in TITLE_REMOVE + COLOR_MAP + LAYOUT_FIXUP:
        if old not in svg:
            print(f"warn: pattern not present in source SVG: {old}")
        svg = svg.replace(old, new)
    svg = re.sub(r'font-size="(\d+)"', _bump_font, svg)

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    OUT_SVG.write_text(svg, encoding="utf-8")
    subprocess.run(
        [rsvg, "-f", "pdf", "-o", str(OUT_PDF), str(OUT_SVG)],
        check=True,
    )
    print(f"wrote {OUT_SVG.relative_to(REPO)}")
    print(f"wrote {OUT_PDF.relative_to(REPO)}")


if __name__ == "__main__":
    main()
