#!/usr/bin/env python3
"""
build_chat_ui.py — Bundle static/js/chat-ui/*.js into static/js/chat-ui.js.

Usage:
    python3 scripts/build_chat_ui.py

Reads modules in dependency order, strips import/export statements, wraps in
an IIFE, and writes the result to static/js/chat-ui.js.  No Node.js or
third-party packages required.
"""

import re
import os
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC_DIR = os.path.join(ROOT, 'static', 'js', 'chat-ui')
OUT_FILE = os.path.join(ROOT, 'static', 'js', 'chat-ui.js')

# Process in dependency order (each file may only import from files listed above it)
MODULE_ORDER = [
    'debug.js',
    'renderers.js',
    'transport.js',
    'turn.js',
    'index.js',
]

# Patterns to strip entirely
_RE_IMPORT_INTERNAL = re.compile(
    r"""^import\s+.*?from\s+['"]\.\/[^'"]+['"]\s*;?\s*$""",
    re.MULTILINE,
)
_RE_EXPORT_LIST = re.compile(
    r"""^export\s*\{[^}]*\}\s*;?\s*$""",
    re.MULTILINE,
)
# Strip `export` keyword but keep the declaration
_RE_EXPORT_DECL = re.compile(
    r"""^export\s+((?:default\s+)?(?:class|function|const|let|var|async\s+function))""",
    re.MULTILINE,
)
# Strip block comments /** ... */ (non-greedy)
_RE_BLOCK_COMMENT = re.compile(r'/\*.*?\*/', re.DOTALL)
# Collapse 3+ consecutive blank lines to 1
_RE_BLANK_LINES = re.compile(r'\n{3,}')


def process_module(path: str, filename: str) -> str:
    with open(path, encoding='utf-8') as f:
        src = f.read()

    # Strip block comments
    src = _RE_BLOCK_COMMENT.sub('', src)
    # Strip internal imports
    src = _RE_IMPORT_INTERNAL.sub('', src)
    # Strip bare re-export lists: export { Foo, Bar }
    src = _RE_EXPORT_LIST.sub('', src)
    # Strip `export` keyword from declarations
    src = _RE_EXPORT_DECL.sub(r'\1', src)
    # Collapse excess blank lines
    src = _RE_BLANK_LINES.sub('\n\n', src)

    return src.strip()


def build():
    parts = []
    for filename in MODULE_ORDER:
        path = os.path.join(SRC_DIR, filename)
        if not os.path.exists(path):
            print(f'ERROR: missing {path}', file=sys.stderr)
            sys.exit(1)
        processed = process_module(path, filename)
        parts.append(f'// ── {filename} {"─" * (60 - len(filename))}\n\n{processed}')
        print(f'  processed {filename} ({len(processed):,} chars)')

    body = '\n\n'.join(parts)
    output = f"""/* chat-ui.js — auto-generated by scripts/build_chat_ui.py
 * Source: static/js/chat-ui/
 * Do not edit this file directly; edit the source modules and re-run the script.
 */
(function () {{
'use strict';

{body}

}})();
"""

    with open(OUT_FILE, 'w', encoding='utf-8') as f:
        f.write(output)

    size_kb = os.path.getsize(OUT_FILE) / 1024
    print(f'\nWrote {OUT_FILE} ({size_kb:.1f} KB)')


if __name__ == '__main__':
    print(f'Building chat-ui.js from {SRC_DIR}...')
    build()
