import re, os, sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
base = os.path.dirname(os.path.abspath(__file__))
fp = os.path.join(base, 'index_main.html')
html = open(fp, encoding='utf-8').read()

# 声明行无空格断言（历史踩坑：final_check/_vd_check 用无空格字面量定位）
assert 'const PROGRAMS=[' in html, "声明行 const PROGRAMS=[ 缺失/被加空格"
assert 'const CATD=[' in html, "声明行 const CATD=[ 缺失/被加空格"

# id -> (旧 n, 新 n)
REN = {
    "nyu-africana-ma": ("Africana Studies (MA)", "非洲裔研究文学硕士（MA）"),
    "nyu-classics-ma": ("Classics (MA)", "古典学文学硕士（MA）"),
    "uchicago-maph": ("Master of Arts Program in the Humanities (MAPH)", "人文研究文学硕士（MAPH）"),
    "col-french-ma": ("French (MA, free-standing)", "法语文学硕士（MA，独立学位）"),
    "col-italian-ma": ("Italian (MA, free-standing)", "意大利语文学硕士（MA，独立学位）"),
    "nyu-german-ma": ("German Thought and Literature (MA)", "德语思想与文学文学硕士（MA）"),
    "ucla-slavic-ma": ("Slavic, East European and Eurasian Languages and Cultures (MA)", "斯拉夫、东欧与欧亚语言文化文学硕士（MA）"),
    "col-german-ma": ("Germanic Languages (MA, free-standing)", "日耳曼语言文学硕士（MA，独立学位）"),
}

# 先定位每个 id 块，确认旧 n 存在且唯一；任一失败则退出不落盘
prog = re.search(r'const PROGRAMS\s*=\s*\[(.*?)\];', html, re.S).group(1)
blocks = dict(re.findall(r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|$)', prog))

for bid, (old, new) in REN.items():
    if bid not in blocks:
        print(f"[ABORT] {bid} 不在 PROGRAMS"); sys.exit(1)
    rest = blocks[bid]
    nm = re.search(r'n:"([^"]*)"', rest)
    if not nm:
        print(f"[ABORT] {bid} 无 n 字段"); sys.exit(1)
    cur = nm.group(1)
    if cur == new:
        print(f"[SKIP] {bid} 已是新名: {new}")
        continue
    if cur != old:
        print(f"[ABORT] {bid} 旧 n 不匹配: 期望『{old}』实际『{cur}』"); sys.exit(1)
    # 块内旧串唯一性
    if rest.count(f'n:"{old}"') != 1:
        print(f"[ABORT] {bid} n 旧串在块内不唯一"); sys.exit(1)

# 定向替换：只在对应 id 块内替换 n 字段
def repl(m):
    bid = m.group(1); rest = m.group(2)
    if bid in REN:
        old, new = REN[bid]
        if f'n:"{old}"' in rest:
            rest = rest.replace(f'n:"{old}"', f'n:"{new}"', 1)
    return '{id:"' + bid + '"' + rest

new_html = re.sub(r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|$)', repl, html)

# 缺逗号自检：删块场景才会出现，本轮不删块；仍检查 }{ 紧贴
bad = re.findall(r'\}\{', new_html)
if bad:
    nbad = len(bad)
    print(f"[ABORT] 发现 {nbad} 处缺逗号(}}{{)"); sys.exit(1)

open(fp, 'w', encoding='utf-8').write(new_html)
print("写入完成，bytes:", len(new_html.encode('utf-8')))

# 复核：新名落地、旧串零残留
for bid, (old, new) in REN.items():
    ok_new = f'n:"{new}"' in new_html
    ok_old = f'n:"{old}"' in new_html
    print(f"{bid}: 新名={ok_new} 旧串残留={ok_old}")
