import re, os, sys, io, json
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
base = os.path.dirname(os.path.abspath(__file__))
html = open(os.path.join(base, 'index_main.html'), encoding='utf-8').read()
m = re.search(r'const PROGRAMS\s*=\s*\[(.*?)\];', html, re.S)
body = m.group(1)
blocks = dict(re.findall(r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|$)', body))

TARGET = ["ucsd-bio-ms","ucsd-bioe-med-ms","ucsd-bioe-ms-med","ucsd-cse-cpss-ms","ucsd-csme-ms",
"ucsd-css-ms","ucsd-dse-ms","ucsd-ece-am-ms","ucsd-es-bb-ms","ucsd-es-ce-ms","ucsd-es-cm-ms",
"ucsd-es-pe-ms","ucsd-mae-ms","ucsd-math-app-ms","ucsd-se-ms"]

def g(rest, key):
    mm = re.search(key+r':"([^"]*)"', rest)
    return mm.group(1) if mm else ''

for tid in TARGET:
    if tid not in blocks:
        print(f"### {tid}: 不在 PROGRAMS"); continue
    r = blocks[tid]
    print(f"### {tid}")
    print(f"  s={g(r,'s')} n={g(r,'n')}")
    print(f"  en={g(r,'en')}")
    print(f"  college={g(r,'college')} deg={g(r,'deg')} dur={g(r,'dur')}")
    print(f"  ddl={g(r,'ddl')} lang={g(r,'lang')} tui={g(r,'tui')}")
    tm=re.search(r'test:\{cls:"([^"]*)"\}', r); print(f"  test={tm.group(1) if tm else ''}")
    print(f"  url={g(r,'url')}")
    # detail page official links
    dp = os.path.join(base, g(r,'url').split('/')[-1]) if '/' in g(r,'url') else os.path.join(base, g(r,'url'))
    dp = os.path.join(base, 'details', g(r,'url').split('/')[-1])
    if os.path.exists(dp):
        t = open(dp, encoding='utf-8').read()
        links = re.findall(r'https?://[^"\'<>\s]+', t)
        off = [u for u in links if 'file:' not in u and not u.startswith('details/') and 'fonts.g' not in u and 'fonts.gstatic' not in u and len(u)>12]
        print(f"  详情页官网链接: {off[:3]}")
    else:
        print("  详情页磁盘缺失!")
    print()
