import re, os, sys, json

base = os.path.dirname(os.path.abspath(__file__))
p = os.path.join(base, "index_main.html")
html = open(p, encoding="utf-8").read()

# 声明行无空格断言（r326 踩坑：final_check/_vd_check 用无空格字面量定位）
assert "const PROGRAMS=[" in html, "PROGRAMS 声明行缺失"
assert "const PROGRAMS =[" not in html and "const PROGRAMS= [" not in html, "PROGRAMS 声明行含空格"
assert "const CATD=[" in html, "CATD 声明行缺失"

RENAME = {
    "ut-mmpa": ("Management and Professional Accounting MMPA", "管理与专业会计硕士（MMPA）"),
    "uva-msa": ("Accounting (MS)", "会计学硕士（MS）"),
    "usc-aeec-ms": ("Applied Economics and Econometrics (MS)", "应用经济学与计量经济学硕士（MS）"),
    "illinois-mspe": ("Policy Economics (MS)", "政策经济学硕士（MS）"),
    "usc-seda-ms": ("Spatial Economics and Data Analysis (MS, SEDA)", "空间经济与数据分析硕士（MS, SEDA）"),
    "berkeley-macss": ("Master of Computational Social Science (MaCSS)", "计算社会科学硕士（MaCSS）"),
    "ut-mmi": ("Management of Innovation MMI", "创新管理硕士（MMI）"),
    "ucsd-bioe-ms-med": ("Bioengineering with Medical Specialization (MS)", "生物工程硕士（MS，医疗方向）"),
}

def block_repl(match):
    bid = match.group(1)
    body = match.group(2)
    if bid in RENAME:
        old, new = RENAME[bid]
        if f'n:"{new}"' in body:
            return match.group(0)  # 幂等：已是新名
        pat = r'n:"' + re.escape(old) + r'"'
        if not re.search(pat, body):
            print(f"!! {bid} 未找到旧 n: {old}")
            sys.exit(2)
        body = re.sub(pat, f'n:"{new}"', body, count=1)
        print(f"OK {bid}: {old} -> {new}")
        return match.group(1) and f'{{id:"{bid}"' + body
    return match.group(0)

# 逐块隔离替换：块以 {id:"xxx", 起始，非贪婪到下一个 {id:"
new_html = re.sub(r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|$)', block_repl, html)

# 缺逗号自检
gap = len(re.findall(r'\}\{', new_html))
print(f"缺逗号 }} {{ 计数: {gap}")
assert gap == 0, "存在 }{ 缺逗号"

# 复核旧串零残留
for bid, (old, new) in RENAME.items():
    if f'n:"{old}"' in new_html:
        print(f"!! {bid} 旧串残留: {old}")
        sys.exit(3)

open(p, "w", encoding="utf-8").write(new_html)
print("written, bytes:", len(new_html.encode("utf-8")))
