# -*- coding: utf-8 -*-
import re, os, sys, io, urllib.request, ssl
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()
p0 = html.index("const PROGRAMS=["); p1 = html.index("const CATD=[")
seg = html[p0:p1]
starts = [m.start() for m in re.finditer(r'\{id:"', seg)]
blocks = {}
for i, a in enumerate(starts):
    b = starts[i+1] if i+1 < len(starts) else len(seg)
    blk = seg[a:b]
    pid = re.search(r'\{id:"([^"]+)"', blk).group(1)
    blocks[pid] = blk

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

ctx = ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
hdr={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"}

def fetch(u, timeout=12):
    try:
        req=urllib.request.Request(u, headers=hdr)
        with urllib.request.urlopen(req, timeout=timeout, context=ctx) as r:
            return r.status, r.read(80000).decode("utf-8","ignore")
    except Exception as e:
        return None, str(e)[:120]

# A) 统一费率总站探测
portals = [
    ("ucla",  "https://www.registrar.ucla.edu/registration/fees-payment/fees"),
    ("usc",   "https://financialaid.usc.edu/graduate/graduate-tuition-and-fees.html"),
    ("ucsd",  "https://registrar.ucsd.edu/finances/fees.html"),
    ("umich", "https://finance.umich.edu/student-billing/tuition-and-fees"),
    ("nyu",   "https://www.nyu.edu/students/students-in-nyu/financial-aid-and-costs/tuition-and-fees/graduate-school-tuition-and-fees.html"),
    ("upenn", "https://www.bursar.upenn.edu/tuition-and-fees"),
    ("stanford","https://registrar.stanford.edu/graduate-students/tuition-and-fees"),
    ("jhu",   "https://studentaffairs.jhu.edu/student-billing/tuition/"),
    ("col",   "https://fao.columbia.edu/costs-and-aid"),
    ("brown", "https://financialaid.brown.edu/cost-of-attendance/"),
]
print("===== A. 统一费率总站 =====")
for tag, u in portals:
    st, body = fetch(u)
    kw = ""
    if st == 200:
        m = re.search(r'.{0,50}(\$\s?[0-9,]{4,}[^ ]{0,12}|[0-9,]{4,}\s?(per credit|/credit|per semester|per term|per year)).{0,30}', body, re.I)
        kw = m.group(0).replace("\n"," ")[:120] if m else "(no $ rate kw in head)"
    print(f"[{tag}] http={st} | {u[:75]}")
    if kw: print("    KW:", kw)

# B) 纯 test 尚未深探的条目：取主记录官网 url，抓 GRE/GMAT 句
test_targets = ["unc-bcb-ms","unc-biology-ms","unc-ese-ms","unc-mcrp","unc-mha",
                "unc-global-studies-ma","unc-media-comm-ma","jhu-c726156","jhu-isai",
                "nyu-applied-stat","nyu-bme","nyu-ds","nyu-meng-me","nyu-mim","nyu-animal-studies-ma",
                "usc-comds-ms","usc-bme","usc-meng-me","usc-mielr-ms","usc-mppds-ms","usc-msds"]
print("\n===== B. 项目页标化/学费关键词 =====")
for tid in test_targets:
    if tid not in blocks:
        print("MISSING", tid); continue
    blk = blocks[tid]
    n=g(blk,'n'); en=g(blk,'en'); deg=g(blk,'deg'); url=g(blk,'url'); tui=g(blk,'tui'); cls=g(blk,'cls')
    st, body = fetch(url) if url else (None,"no url")
    tk=""; tw=""
    if st==200:
        mt=re.search(r'.{0,50}(GRE|GMAT).{0,70}', body)
        tk=mt.group(0).replace("\n"," ")[:130] if mt else "(no GRE/GMAT)"
        mf=re.search(r'.{0,40}(\$\s?[0-9,]{3,}|tuition|per credit).{0,50}', body, re.I)
        tw=mf.group(0).replace("\n"," ")[:110] if mf else ""
    print(f"[{tid}] {n[:26]} | {deg} | http={st} | tui={'Y' if tui else '-'} cls={'Y' if cls else '-'}")
    print(f"    test: {tk}")
    if tw: print(f"    fee : {tw}")
