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 踩坑）
assert "const PROGRAMS=[" in html and "const CATD=[" in html
assert "const PROGRAMS =[" not in html and "const PROGRAMS= [" not in html

before_n = len(re.findall(r'\{id:"', html))

# ---------- 1. 删除重复占位块 uva-msa（连同块尾逗号；前导逗号保留给前后衔接） ----------
m_block = re.search(r'\{id:"uva-msa",[\s\S]*?url:"details/uva-msa\.html"\},', html)
assert m_block, "uva-msa 块未定位"
old_block = m_block.group(0)
html = html[:m_block.start()] + html[m_block.end():]
print("删除重复块 uva-msa，块长:", len(old_block))

# ---------- 2. VD 摘除 details/uva-msa.html（中间元素，连同前导逗号） ----------
vd_target = '"details/uva-msa.html"'
assert html.count(vd_target) == 1, f"VD 摘除前残留次数异常: {html.count(vd_target)}"
html = html.replace("," + vd_target, "")
assert vd_target not in html, "VD 摘除后仍残留"
print("VD 摘除 details/uva-msa.html")

# ---------- 3. 保留条 uva-msacc：n 规范化 + en 补全全称 ----------
def patch_block(html, bid, patches):
    """在 {id:"bid",...} 块内定向替换字段；patches: {field: (old, new)}"""
    m = re.search(r'\{id:"' + re.escape(bid) + r'",[\s\S]*?(?=\{id:"|$)', html)
    assert m, f"{bid} 块未定位"
    block = m.group(0)
    new_block = block
    for field, (old, new) in patches.items():
        pat = field + r':"' + re.escape(old) + r'"'
        if not re.search(pat, new_block):
            print(f"!! {bid} 字段 {field} 未找到旧值: {old}"); sys.exit(2)
        new_block = re.sub(pat, field + r':"' + new + r'"', new_block, count=1)
    html = html[:m.start()] + new_block + html[m.end():]
    print(f"OK {bid} 字段更新: {list(patches.keys())}")
    return html

html = patch_block(html, "uva-msacc", {
    "n": ("会计硕士", "会计学硕士（MS）"),
    "en": ("Accounting (MS)", "Master of Science in Accounting (McIntire School of Commerce)"),
})

# ---------- 4. 8 条译名（块内定向替换 n） ----------
RENAME = {
    "ut-mmpa": ("Management and Professional Accounting MMPA", "管理与专业会计硕士（MMPA）"),
    "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，医疗方向）"),
    "umich-aero-mse": ("Aerospace Engineering MSE", "航空航天工程硕士（MSE）"),
}
for bid, (old, new) in RENAME.items():
    html = patch_block(html, bid, {"n": (old, new)})

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

for bid, (old, new) in RENAME.items():
    if f'n:"{old}"' in html:
        print(f"!! {bid} 旧 n 残留"); sys.exit(3)

after_n = len(re.findall(r'\{id:"', html))
print(f"PROGRAMS 块数: {before_n} -> {after_n}")
assert after_n == before_n - 1, "应仅减少 1 条重复块"

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