#!/usr/bin/env python3
"""將 web/ 打包成單一 HTML 檔（方便傳檔；仍須用 http 伺服器開啟，不能雙擊 file://）。"""
from __future__ import annotations
import base64
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent / "web"
OUT = ROOT / "pich2pich-all-in-one.html"


def read(p: Path) -> str:
    return p.read_text(encoding="utf-8")


def inline_scripts(html: str) -> str:
    def repl(m: re.Match[str]) -> str:
        src = m.group(1)
        if src.startswith("http"):
            return m.group(0)
        return f"<script>\n{read(ROOT / src)}\n</script>"

    return re.sub(r'<script\s+src="([^"]+)"\s*></script>', repl, html)


def inline_css(html: str) -> str:
    def repl_link(m: re.Match[str]) -> str:
        href = m.group(1)
        if href.startswith("http"):
            return m.group(0)
        return f"<style>\n{read(ROOT / href)}\n</style>"

    html = re.sub(r'<link[^>]+href="([^"]+\.css)"[^>]*/>', repl_link, html)
    return html


def png_data_url(path: Path) -> str:
    b64 = base64.standard_b64encode(path.read_bytes()).decode()
    return f"data:image/png;base64,{b64}"


def main() -> None:
    html = read(ROOT / "index.html")
    html = inline_css(html)
    html = inline_scripts(html)
    html = html.replace('href="icon-192.png"', f'href="{png_data_url(ROOT / "icon-192.png")}"')
    html = html.replace('href="manifest.webmanifest"', 'href="#"')
    html = re.sub(r'<link rel="manifest"[^>]*/>', "<!-- manifest inlined -->\n", html)
    banner = "<!-- Pich2Pich single-file bundle. Serve via http(s), open in Google Chrome. -->\n"
    OUT.write_text(banner + html, encoding="utf-8")
    print(f"Wrote {OUT} ({OUT.stat().st_size // 1024} KB)")


if __name__ == "__main__":
    main()
