#!/usr/bin/env python3
"""lane_nav.py — one menu on every review page this lane writes.

Operator, 2026-08-22: "each page should have a menu so you can go to each page." Five
scripts write HTML (storyboard, submit contract, library, cut, review board) and the
portal writes four more (run, review, preview, gallery); none linked to the others, so
a reviewer had to know the file names. `inject_nav(path)` is called by every writer
after it writes: it lists every surface that EXISTS for the project (so a link is never
dead), marks the current one, and resolves paths relative to the page itself.

Usage from a writer:   from lane_nav import inject_nav; inject_nav(html_path)
Standalone:            lane_nav.py <page.html> [...]   (re-inject after pages change)
"""
from __future__ import annotations

import glob
import html
import os
import re
import sys

MARK_OPEN, MARK_CLOSE = "<!-- lane-nav -->", "<!-- /lane-nav -->"


def _project_dir(page: str) -> str:
    d = os.path.dirname(os.path.abspath(page))
    return os.path.dirname(d) if os.path.basename(d) == "build" else d


def surfaces(project_dir: str) -> list[tuple[str, str]]:
    """(label, absolute path) for every surface that exists, in review order."""
    b = os.path.join(project_dir, "build")
    fixed = [
        ("Storyboard", os.path.join(b, "storyboard.html")),
        ("Vocal brief", os.path.join(b, "vocal-brief.html")),
        ("Song breakdown", os.path.join(b, "song-breakdown.html")),
        ("Submit contract", os.path.join(b, "submit-contract.html")),
        ("First take", os.path.join(b, "first-take.html")),
        ("Draws", os.path.join(b, "draws-review.html")),
        ("Sync", os.path.join(b, "sync-review.html")),
        ("Run", os.path.join(project_dir, "run.html")),
        ("Library", os.path.join(b, "library.html")),
    ]
    cuts = [("Cut " + os.path.basename(p)[4:-5], p) for p in sorted(glob.glob(os.path.join(b, "cut-*.html")))]
    boards = [("Board " + os.path.basename(p)[7:-5], p) for p in sorted(glob.glob(os.path.join(b, "review-*.html")))]
    tail = [
        ("Review", os.path.join(project_dir, "review.html")),
        ("Preview", os.path.join(project_dir, "preview.html")),
        ("Gallery", os.path.join(project_dir, "gallery.html")),
    ]
    return [(l, p) for l, p in fixed + cuts + boards + tail if os.path.isfile(p)]


def nav_html(page: str) -> str:
    here = os.path.abspath(page)
    items = []
    for label, path in surfaces(_project_dir(here)):
        rel = os.path.relpath(path, os.path.dirname(here))
        cur = ' class="cur"' if os.path.abspath(path) == here else ""
        items.append(f'<a href="{html.escape(rel)}"{cur}>{html.escape(label)}</a>')
    return (f'{MARK_OPEN}<nav class="lane-nav"><span>rap-mv</span>{"".join(items)}</nav>'
            # on the portal's tokens (lane_page) with literal fallbacks for a page written
            # before the shell — the menu reads the same on every surface (film3 item 12)
            '<style>.lane-nav{display:flex;flex-wrap:wrap;gap:6px;align-items:center;'
            'font:13px/1.2 var(--font-body,-apple-system,BlinkMacSystemFont,sans-serif);margin:0 0 18px;padding:8px 10px;'
            'border:1px solid var(--line,#333);border-radius:8px;background:var(--panel,#15171c)}'
            '.lane-nav span{color:var(--ink3,#888);margin-right:6px}'
            '.lane-nav a{color:var(--accent,#e8c36a);text-decoration:none;padding:4px 9px;border-radius:6px;background:var(--panel2,#22252c)}'
            f'.lane-nav a.cur{{background:var(--accent,#e8c36a);color:var(--bg,#111)}}</style>{MARK_CLOSE}')


def inject_nav(page: str) -> None:
    """Insert (or refresh) the menu at the top of the page's visible content."""
    if not os.path.isfile(page):
        return
    doc = open(page, encoding="utf-8").read()
    doc = re.sub(re.escape(MARK_OPEN) + ".*?" + re.escape(MARK_CLOSE), "", doc, flags=re.S)
    nav = nav_html(page)
    for anchor in ("<body>", "<h1"):
        i = doc.find(anchor)
        if i >= 0:
            if anchor == "<body>":
                i += len("<body>")
            doc = doc[:i] + nav + doc[i:]
            break
    else:
        j = doc.find("</style>")
        doc = (doc[:j + 8] + nav + doc[j + 8:]) if j >= 0 else doc + nav
    open(page, "w", encoding="utf-8").write(doc)


if __name__ == "__main__":
    for p in sys.argv[1:]:
        inject_nav(p)
        print(f"lane_nav: {p}")
