import json, re, sys
from pathlib import Path

root = Path(r"D:\work buddy\2026-11-05-14-15-52")
html = (root / "index_main.html").read_text(encoding="utf-8")

# Extract PROGRAMS block
m = re.search(r"const\s+PROGRAMS\s*=\s*\[", html)
if not m:
    print("PROGRAMS not found"); sys.exit(1)
start = m.end()
# bracket depth scan
depth = 1
i = start
while i < len(html) and depth > 0:
    c = html[i]
    if c == "[": depth += 1
    elif c == "]": depth -= 1
    i += 1
block = html[start:i-1]

# Parse each {id:"...", ...}
items = {}
# regex: id:"..." then collect until next {id: or end
for m in re.finditer(r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|$)', block):
    pid = m.group(1)
    body = m.group(2)
    def grab(key):
        mm = re.search(re.escape(key)+r':"([^"]*)"', body)
        return mm.group(1) if mm else ""
    items[pid] = {
        "s": grab("s"),
        "n": grab("n"),
        "en": grab("en"),
        "deg": grab("deg"),
        "url": grab("url"),
    }

print(f"Current PROGRAMS parsed: {len(items)}")

# Load snapshot
snap = json.loads((root / "_daily_snapshot.json").read_text(encoding="utf-8"))
old = snap.get("programs", {})
print(f"Snapshot count: {len(old)} (snapshot_at {snap.get('snapshot_at')})")

# Diff
new_ids = []
url_changed = []
for pid, rec in items.items():
    if pid not in old:
        new_ids.append(pid)
    elif old[pid].get("url") != rec["url"]:
        url_changed.append((pid, old[pid].get("url"), rec["url"]))

print(f"New IDs: {len(new_ids)}")
for pid in new_ids:
    print(f"  + {pid}  s={items[pid]['s']} n={items[pid]['n']} deg={items[pid]['deg']} url={items[pid]['url']}")

print(f"URL changed: {len(url_changed)}")
for pid, old_url, new_url in url_changed:
    print(f"  ~ {pid}  {old_url} -> {new_url}")

# Write back snapshot
out = {
    "snapshot_at": "2026-11-26 09:30:00",
    "count": len(items),
    "programs": items,
}
(root / "_daily_snapshot.json").write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"Snapshot written: {len(items)} entries")
