import re, os, sys

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

# 声明行无空格断言
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. 删除重复占位块 + VD 摘除 ----------
MERGE = [
    ("ut-mscsm", "details/ut-mscsm.html"),
    ("usc-me-em-dual", "details/usc-me-em-dual.html"),
]
for bid, url in MERGE:
    m = re.search(r'\{id:"' + re.escape(bid) + r'",[\s\S]*?url:"' + re.escape(url) + r'"\}\s*,', html)
    assert m, f"{bid} 块未定位"
    html = html[:m.start()] + html[m.end():]
    print(f"删除重复块 {bid}，块长 {len(m.group(0))}")

    vd_seg = re.search(r"const VERIFIED_DETAILS[^;]+;", html).group(0)
    assert vd_seg.count('"' + url + '"') == 1, f"{url} VD 次数异常"
    # 中间元素：连同前导逗号摘除
    html = html.replace(',"' + url + '"', '')
    assert ('"' + url + '"') not in html, f"{url} 摘除后残留"
    print(f"VD 摘除 {url}")

# ---------- 2. 块内定向译名 ----------
def patch_block(html, bid, field, old, new):
    m = re.search(r'\{id:"' + re.escape(bid) + r'",[\s\S]*?(?=\{id:"|$)', html)
    assert m, f"{bid} 块未定位"
    block = m.group(0)
    pat = field + r':"' + re.escape(old) + r'"'
    if f'{field}:"{new}"' in block:
        print(f"OK {bid} 已是新名（幂等跳过）")
        return html
    if not re.search(pat, block):
        print(f"!! {bid} 字段 {field} 未找到旧值: {old}"); sys.exit(2)
    new_block = re.sub(pat, field + r':"' + new + r'"', block, count=1)
    return html[:m.start()] + new_block + html[m.end():]

RENAME = {
    "berkeley-cbe-pdp": ("Chemical Biomolecular Engineering Professional MS", "化学与生物分子工程硕士（MS，产品开发方向）"),
    "ucsd-se-ms": ("Structural Engineering MS", "结构工程硕士（MS）"),
    "uva-se-ms": ("Systems Engineering MS", "系统工程硕士（MS）"),
    "ubc-mppga": ("Public Policy and Global Affairs (MPPGA)", "公共政策与全球事务硕士（MPPGA）"),
    "usc-hsme-ms": ("Health Systems Management Engineering (MS)", "健康系统管理工程硕士（MS）"),
    "usc-mnlm": ("Nonprofit Leadership and Management (MNLM)", "非营利组织领导与管理硕士（MNLM）"),
}
for bid, (old, new) in RENAME.items():
    html = patch_block(html, bid, "n", old, new)
    print(f"OK {bid}: {old} -> {new}")

# ---------- 3. 自检 ----------
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}（应 -2）")
assert after_n == before_n - 2, "应仅减少 2 条重复块"

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