#!/usr/bin/env python3
"""Inline the ES modules in js/ into index.html so the page also works from a file:// URL.

    python3 build.py            # rebuilds index.html from dev.html + js/*.js

dev.html is the modular development page (serve the folder over HTTP to use it);
index.html is the self-contained build. Each module is wrapped in its own scope, so
module-level names never collide, and only the pinned three.js CDN import remains external.
"""
import re, pathlib

ROOT = pathlib.Path(__file__).parent
ORDER = ['util', 'city', 'jellyfish', 'props', 'traffic', 'rain', 'effects', 'cameras', 'main']

def transform(name, src):
    exports, body = [], []
    for line in src.split('\n'):
        m = re.match(r"^import \* as THREE from 'three';\s*$", line)
        if m: continue
        m = re.match(r"^import \{([^}]*)\} from '\./(\w+)\.js';\s*$", line)
        if m:
            body.append(f"const {{{m.group(1)}}} = __{m.group(2)};")
            continue
        m = re.match(r"^export (const|let|function|class) (\w+)", line)
        if m:
            exports.append(m.group(2)); line = line[len('export '):]
        body.append(line)
    assert 'import ' not in '\n'.join(l for l in body if l.startswith('import')), name
    ret = ('  return { ' + ', '.join(exports) + ' };\n') if exports else ''
    return f"// ===== js/{name}.js =====\nconst __{name} = (() => {{\n" + '\n'.join(body) + f"\n{ret}}})();\n"

def main():
    html = (ROOT / 'dev.html').read_text()
    modules = '\n'.join(transform(n, (ROOT / 'js' / f'{n}.js').read_text()) for n in ORDER)
    assert '</script' not in modules
    inline = ("<script type=\"module\">\n// Built by build.py from js/*.js — edit the modules and rebuild; dev.html loads them directly.\n"
              "import * as THREE from 'three';\n" + modules + "</script>")
    out, n = re.subn(r'<script type="module" src="\./js/main\.js"></script>', lambda _: inline, html)
    assert n == 1, 'module script tag not found in dev.html'
    (ROOT / 'index.html').write_text(out)
    print(f'index.html built: {len(out)//1024} KB from {len(ORDER)} modules')

if __name__ == '__main__':
    main()
