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()

# 断言声明行无空格原样
assert 'const PROGRAMS=[' in html, "PROGRAMS 声明行无空格断言失败"
assert 'const CATD=[' in html, "CATD 声明行无空格断言失败"

renames = [
    ("col-mesaas-ma", "Middle Eastern, South Asian, and African Studies (MA)", "中东、南亚与非洲研究文学硕士（MA, MESAAS）"),
    ("nyu-cinema-ma", "Cinema Studies (MA)", "电影研究文学硕士（MA）"),
    ("nyu-hebrew-ma", "Hebrew and Judaic Studies (MA)", "希伯来与犹太研究文学硕士（MA）"),
    ("col-religion-ma", "Religion (MA, free-standing)", "宗教学文学硕士（MA，独立学位）"),
]

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))

applied = []
for tid, old_n, new_n in renames:
    if tid not in blocks:
        print(f"!! {tid} NOT IN PROGRAMS, abort"); sys.exit(1)
    rest = blocks[tid]
    # 幂等：已是新名则跳过
    if f'n:"{new_n}"' in rest:
        print(f"== {tid} 已是新名，跳过")
        continue
    old_pat = f'n:"{old_n}"'
    if rest.count(old_pat) != 1:
        print(f"!! {tid} 旧 n 串出现 {rest.count(old_pat)} 次（应为1），abort"); sys.exit(1)
    # 块内定向替换
    new_rest = rest.replace(old_pat, f'n:"{new_n}"', 1)
    old_block = '{id:"' + tid + '"' + rest
    new_block = '{id:"' + tid + '"' + new_rest
    if html.count(old_block) != 1:
        print(f"!! {tid} 块定位失败（出现 {html.count(old_block)} 次），abort"); sys.exit(1)
    html = html.replace(old_block, new_block, 1)
    applied.append(tid)
    print(f"OK {tid}: {new_n}")

# 缺逗号自检
gap = html.count('}{')
print("缺逗号 } { 计数:", gap)
if gap != 0:
    print("!! 存在缺逗号，abort"); sys.exit(1)

# 旧英文串残留检查（在全文件）
for tid, old_n, new_n in renames:
    if old_n in html:
        print(f"!! {tid} 旧串仍残留"); sys.exit(1)

open(fp, 'w', encoding='utf-8').write(html)
print("written, applied:", applied)
