#!/usr/bin/env python3
"""build.py — embed public/index.html into vgo.c as INDEX_HTML[], then compile."""
import os, sys

HERE = os.path.dirname(os.path.abspath(__file__))
CFILE = os.path.join(HERE, "vgo.c")
HTML  = os.path.join(HERE, "public", "index.html")

def esc_c(s):
    # convert string -> C escaped
    return "".join(
        "\\x%02x" % ord(c) if (ord(c) < 0x20 and c not in "\t") else
        "\\t" if c == "\t" else
        "\\n" if c == "\n" else
        "\\r" if c == "\r" else
        "\\\\" if c == "\\" else
        '\\"' if c == '"' else c
        for c in s
    )

def build():
    with open(HTML, "r", encoding="utf-8") as f:
        html = f.read()
    chunk = esc_c(html)
    # Build line-by-line output; break into chunks <= 200 chars
    lines = ['const char INDEX_HTML[] = {']
    i = 0
    while i < len(chunk):
        seg = chunk[i:i+200]
        lines.append('    "' + seg + '",')
        i += 200
    lines.append('    0');  # null terminator
    lines.append('};')
    lines.append('')
    embed = "\n".join(lines)

    # Read vgo.c, replace existing INDEX_HTML[] block (if any) or append
    with open(CFILE, "r", encoding="utf-8") as f:
        src = f.read()
    marker = "const char INDEX_HTML[] = {"
    if marker in src:
        start = src.index(marker)
        # find the closing }; after this block
        end = src.index("};", start) + 2
        src = src[:start] + embed + "\n\n" + src[end:]
    else:
        src = src.rstrip() + "\n\n" + embed + "\n"
    with open(CFILE, "w", encoding="utf-8") as f:
        f.write(src)
    print("[build] embedded index.html -> vgo.c (%d bytes)" % len(html))

if __name__ == "__main__":
    build()
