# -*- coding: utf-8 -*-
import sys, io, re, json, pathlib, html as H
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
CACHE = pathlib.Path(r"D:\work buddy\2026-11-05-14-15-52\cache")

def txt(x):
    x = re.sub(r"<[^>]+>", " ", x)
    return re.sub(r"\s+", " ", H.unescape(x)).strip()

def parse(path):
    raw = path.read_text(encoding="utf-8", errors="ignore")
    i = raw.find('id="requirementstextcontainer"')
    j = raw.find('id="designatorsandoptionstextcontainer"')
    seg = raw[i:j] if j > i else raw[i:]
    out = {"headings": [], "paras": [], "courses": [], "sections": []}
    # split by h5 headings
    parts = re.split(r'<h5[^>]*>', seg)
    for part in parts[1:]:
        h = txt(re.split(r'</h5>', part)[0])
        body = part.split('</h5>', 1)[1] if '</h5>' in part else ""
        rows = re.findall(r'<tr[^>]*>(.*?)</tr>', body, re.S)
        crs = []
        for r in rows:
            m = re.search(r'class="codecol"[^>]*>(.*?)</td>', r, re.S)
            t = re.search(r'class="titlecol"[^>]*>(.*?)</td>', r, re.S)
            hh = re.search(r'class="hourscol"[^>]*>(.*?)</td>', r, re.S)
            if m and t:
                code = txt(m.group(1))
                if code:
                    crs.append([code, txt(t.group(1)), txt(hh.group(1)) if hh else ""])
        out["sections"].append({"h": h, "courses": crs, "text": txt(re.sub(r'<table.*?</table>', ' ', body, flags=re.S))[:600]})
    return out

data = {}
for k in ["gatech-cs", "gatech-analytics", "gatech-stat", "gatech-me", "gatech-bioinfo", "gatech-hci"]:
    d = parse(CACHE / (k + ".html"))
    data[k] = d
    print("=" * 15, k, "sections", len(d["sections"]), "codes", sum(len(s["courses"]) for s in d["sections"]))
    for s in d["sections"][:14]:
        print("  H:", s["h"], "| courses", len(s["courses"]), "|", s["text"][:160].replace("\n", " "))
        for c in s["courses"][:3]:
            print("      ", c)
(pathlib.Path(CACHE.parent) / "_r342_parsed.json").write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
print("saved")
