#!/usr/bin/env python3
"""Extract each page's inline <script> body to /static/js/pages/{page}.js
and replace the inline block with an external src reference.

Why: the app enforces CSP `script-src 'self'` (no unsafe-inline), which blocks
inline scripts. External same-origin files comply without weakening security.
"""
import re
import sys
from pathlib import Path

STATIC = Path(__file__).resolve().parent.parent / "static"
PAGES_DIR = STATIC / "js" / "pages"
PAGES_DIR.mkdir(parents=True, exist_ok=True)

INLINE_RE = re.compile(r"<script>(.*?)</script>", re.S)

def process(html_path: Path) -> str:
    src = html_path.read_text(encoding="utf-8")
    name = html_path.stem
    blocks = list(INLINE_RE.finditer(src))
    out = []
    changed = False
    last = 0
    for m in blocks:
        body = m.group(1)
        if not body.strip():
            continue  # placeholder or empty
        # only extract the page-boot script (the one defining pageBoot / login logic)
        if "pageBoot" not in body and "login" not in name:
            continue
        js_path = PAGES_DIR / f"{name}.js"
        js_path.write_text(body.strip() + "\n", encoding="utf-8")
        out.append(src[last:m.start()])
        out.append(f'<script src="/static/js/pages/{name}.js"></script>')
        last = m.end()
        changed = True
    if not changed:
        return "skip"
    out.append(src[last:])
    html_path.write_text("".join(out), encoding="utf-8")
    return f"extracted -> js/pages/{name}.js"

def main():
    for html_path in sorted(STATIC.glob("*.html")):
        print(f"{html_path.name}: {process(html_path)}")

if __name__ == "__main__":
    sys.exit(main())
