import json, re, os
here = os.path.dirname(os.path.abspath(__file__))
tpl = open(os.path.join(here, "template.html")).read()
data = open(os.path.join(here, "data.json")).read()
assert "__DATA__" in tpl, "placeholder missing"
out = tpl.replace("__DATA__", data)
assert "__DATA__" not in out
p = os.path.join(here, "sf-block-score.html")
open(p, "w").write(out)
print("wrote sf-block-score.html: %d KB" % (len(out) // 1024))

# ---- structural verification (no browser needed) ----
errs = []
# no doctype/html/head/body wrappers (Artifact supplies the skeleton)
for bad in ("<!doctype", "<!DOCTYPE", "<html", "<head>", "<body"):
    if bad in out: errs.append("contains %s" % bad)
if out.count("<title>") != 1: errs.append("title count != 1")
# every var(--token) referenced must be defined in the bare :root block
root = re.search(r":root\{(.*?)\}", out, re.S).group(1)
defined = set(re.findall(r"(--[a-z0-9-]+)\s*:", root))
used = set(re.findall(r"var\((--[a-z0-9-]+)", out))
missing = sorted(used - defined)
if missing: errs.append("tokens used but not in bare :root: %s" % missing)
# balanced tags for the elements we author
for t in ("div", "span", "svg", "script", "style", "button", "ol", "li", "p", "ul", "h1", "h2", "h3"):
    o = len(re.findall(r"<%s[\s>]" % t, out)); c = out.count("</%s>" % t)
    if o != c: errs.append("<%s> %d open vs %d close" % (t, o, c))
# data sanity
d = json.loads(data)
n = d["meta"]["n"]
if len(d["cells"]["lat"]) != n: errs.append("cell length mismatch")
for k, v in d["scores"].items():
    if len(v) != n: errs.append("scores[%s] length %d != %d" % (k, len(v), n))
for k, v in d["raw"].items():
    if len(v) != n: errs.append("raw[%s] length %d != %d" % (k, len(v), n))
keys = {f["key"] for f in d["factors"]}
if keys != set(d["scores"].keys()): errs.append("factor/score key mismatch")
# every factor must belong to a group and carry a known provenance
for f in d["factors"]:
    if f["prov"] not in ("MEASURED", "DERIVED", "ENCODED"): errs.append("bad prov %s" % f["key"])
print("VERIFY:", "ALL CHECKS PASSED" if not errs else "FAILED")
for e in errs: print("  !", e)
