#!/usr/bin/env python3
"""Assemble the self-contained review page published as a Claude Artifact.

Everything is inlined: stylesheet, all 33 page sections, every SVG figure and
every photograph. The page keeps its own source as three JS constants so it can
republish itself carrying the comment list, which is how comments become
visible to every viewer.
"""
import base64, json, os, re, urllib.parse

ROOT = os.path.join(os.path.dirname(__file__), "..")
P = lambda *a: os.path.join(ROOT, *a)


def js(s):
    """JSON string that cannot terminate the enclosing <script>."""
    return json.dumps(s).replace("</", "<\\/")


def read(*a):
    with open(P(*a), encoding="utf-8") as f:
        return f.read()


def svg_uri(path):
    raw = read(path)
    raw = re.sub(r"\s+", " ", raw).strip()
    return "data:image/svg+xml;charset=utf-8," + urllib.parse.quote(raw, safe="")


def jpg_uri(path):
    with open(P(path), "rb") as f:
        return "data:image/jpeg;base64," + base64.b64encode(f.read()).decode()


def inline(markup):
    """Replace every ../assets/... reference with a data: URI."""
    cache = {}

    def uri_for(rel):
        if rel in cache:
            return cache[rel]
        path = rel.replace("../", "")
        if rel.startswith("../assets/img/"):
            path = path.replace("assets/img/", "assets/web/")   # web-sized photos
        u = jpg_uri(path) if path.endswith(".jpg") else svg_uri(path)
        cache[rel] = u
        return u

    markup = re.sub(r'src="(\.\./assets/[^"]+)"',
                    lambda m: 'src="' + uri_for(m.group(1)) + '"', markup)
    markup = re.sub(r'url\((\.\./assets/[^)]+)\)',
                    lambda m: 'url(' + uri_for(m.group(1)) + ')', markup)
    return markup


CSS = read("css", "okelis.css") + "\n" + read("review", "artifact.css")
PAGES = inline(read("review", "pages.html"))
APP = read("review", "artifact.js")

DOC = (
    '<!doctype html>\n<html lang="en"><head><meta charset="utf-8">'
    '<meta name="viewport" content="width=device-width,initial-scale=1">'
    "<title>OKELIS Portfolio Review</title></head>\n<body>\n<script>\n"
    "const CSS=" + js(CSS) + ";\n"
    "const PAGES=" + js(PAGES) + ";\n"
    "const APP=" + js(APP) + ";\n"
    "let NOTES=[];\n"
    "new Function('CSS','PAGES','APP','NOTES',APP)(CSS,PAGES,APP,NOTES);\n"
    "</script>\n</body></html>\n"
)

out = P("dist", "okelis-review-artifact.html")
with open(out, "w", encoding="utf-8") as f:
    f.write(DOC)
print(f"→ {out}  {len(DOC)/1_048_576:.2f} MB")
