# -*- coding: utf-8 -*-
import io, sys, os, re, html, json
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
B = r"D:\work buddy\2026-11-05-14-15-52"
h = open(os.path.join(B,"raw_unc.html"),encoding="utf-8").read()
i = h.find('id="byorgtextcontainer"')
j = h.find('id="bynametextcontainer"')
seg = h[i:j if j>0 else len(h)]
ps = re.findall(r'<p class="body"([^>]*)>(.*?)</p>', seg, re.S)

DEG_RE = re.compile(r"M\.A\.|M\.S\.|Ph\.?D\.|Dr\.?P\.?H\.?|M\.P\.H\.|M\.S\.P\.H\.|M\.P\.A\.|M\.F\.A\.|M\.Ed\.|Ed\.D\.|M\.C\.R\.P\.|M\.S\.I\.S\.|M\.S\.L\.S\.|M\.A\.D\.S\.|M\.P\.S\.|M\.A\.P\.S\.|M\.H\.A\.|M\.S\.W\.|M\.A\.T\.|D\.N\.P\.|M\.S\.N\.|M\.S\.E\.E\.|M\.S\.C\.R\.|DDS|D\.D\.S\.", re.I)
BRANCH = {"Residential","Distance","Distance and Site-based","Top-level"}

rows=[]; current_group=None; current_sub=None
for attr,p in ps:
    hrefs = re.findall(r'href="([^"]+)"', p)
    url = "https://catalog.unc.edu"+hrefs[0] if hrefs else ""
    full = html.unescape(re.sub(r"<[^>]+>","",p)).replace("\xa0"," ")
    lead = len(full)-len(full.lstrip(" ")); full=full.strip()
    if not full: continue
    if "–" in full: name, deg = full.split("–",1)
    elif "-" in full: name, deg = full.split("-",1)
    else: name, deg = full, ""
    name=name.strip().strip("•").strip(); deg=deg.strip(" ,")
    has_deg = bool(DEG_RE.search(deg))
    indent = ("margin-left" in attr) or lead>=3
    if not has_deg:
        current_group=name; current_sub=None
        continue
    if not indent:
        current_group=name; college=name
    else:
        college=current_group
    if name in BRANCH:
        name = current_sub or current_group
        rows.append({"college":current_group,"name":name,"deg":deg,"url":url,"kind":"branch"})
    else:
        rows.append({"college":college,"name":name,"deg":deg,"url":url,"kind":"sub"})
        current_sub=name

json.dump(rows, open(os.path.join(B,"raw_unc.json"),"w",encoding="utf-8"), ensure_ascii=False, indent=1)
print("结构化行:", len(rows))
for r in rows:
    print(f"{r['kind']:6}|{(r['college'] or '-')[:28]:28}|{r['name'][:40]:40}|{r['deg'][:22]}")
