#!/usr/bin/env python3
"""
build.py — Inline body-clean.html into index.html for a true single-file deployable.

SmartPantry rebuild strategy:
- body-clean.html has the markup (extracted from the de-Google'd source)
- styles.css has the CSS (extracted from the de-Google'd source)
- app-firebase-stubs.js has the no-op Firebase globals
- app-households.js has the household management code
- app-main.js has the main app logic
- app-modals.js has the modal/widget code
- app-bootstrap.js has the init/DOMContentLoaded glue
- index.html pulls it all together

The build step inlines body-clean.html into index.html so the result is a single
deployable HTML file (with separate JS files referenced).
"""

import sys
import re
from pathlib import Path

ROOT = Path(__file__).parent.parent
APP = ROOT / "app"

INDEX_HTML = APP / "index.html"
BODY_HTML = APP / "body-clean.html"


def inline_body():
    index_content = INDEX_HTML.read_text()
    body_content = BODY_HTML.read_text().strip()

    # Replace BOTH:
    # 1. The empty <main id="app-root"></main> placeholder
    # 2. The fetch() script that was supposed to fill it
    # ...with one inlined <main> that contains the body markup.

    placeholder_pattern = re.compile(
        r'<main id="app-root">\s*</main>',
        re.DOTALL
    )
    fetch_pattern = re.compile(
        r'<!-- Load body markup -->\s*<script>.*?</script>',
        re.DOTALL
    )

    replacement = f"""<main id="app-root">
{body_content}
</main>"""

    new_content = placeholder_pattern.sub(replacement, index_content)
    new_content = fetch_pattern.sub('', new_content)

    output_path = APP / "index-built.html"
    output_path.write_text(new_content)

    print(f"✓ Inlined {len(body_content):,} bytes of body markup")
    print(f"✓ Output: {output_path}")
    print(f"  Size: {len(new_content):,} bytes")
    return output_path


if __name__ == "__main__":
    inline_body()
