import re, os, sys, io
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 = re.findall(r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|$)', body)

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

targets = {"nyu-africana-ma","nyu-classics-ma","uchicago-maph","col-french-ma",
           "col-italian-ma","nyu-german-ma","ucla-slavic-ma","col-german-ma",
           "col-mesaas-ma","nyu-cinema-ma","nyu-hebrew-ma","col-religion-ma"}

# 按学校分组，看同校内 en 关键词重叠
by_school = {}
for bid, rest in blocks:
    s = g(rest,'s')
    by_school.setdefault(s, []).append((bid, g(rest,'en'), g(rest,'n'), g(rest,'url')))

for t in targets:
    for bid, rest in blocks:
        if bid != t: continue
        s = g(rest,'s'); en = g(rest,'en')
        print(f"== {t} school={s} en={en}")
        for obid, oen, on, ourl in by_school.get(s, []):
            if obid == t: continue
            # 关键词重叠
            kw = [w for w in re.findall(r'[A-Za-z]{5,}', en) if w.lower() not in ('master','arts','department','free','standing','gsas','studies','program','language','languages','literatures','literature','east','european','eurasian','slavic')]
            if any(k.lower() in oen.lower() for k in kw[:3]):
                print(f"   同校近邻: {obid} | {on} | {oen} | {ourl}")
        print()
