# -*- coding: utf-8 -*-
import io, sys, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
p = "index_main.html"
html = open(p, encoding="utf-8").read()
orig = html

DET = "details/cornell-c7bcf8e.html"

# 1) 还原 PROGRAMS 中被误改的 umich-cse url
bad = 'url:"details/umich-cse.html","details/cornell-c7bcf8e.html"'
good = 'url:"details/umich-cse.html"'
if bad in html:
    html = html.replace(bad, good, 1)
    print("已还原误改的 umich-cse PROGRAMS url")
else:
    print("未发现误改串，跳过还原")

# 2) 仅在 VD 段内补登记 DET（正则限定段内，避免误伤 PROGRAMS/CATD）
vm = re.search(r'(const VERIFIED_DETAILS=new Set\(\[)(.*?)(\]\);)', html, re.S)
assert vm, "VD 段未找到"
vd_body = vm.group(2)
if ('"' + DET + '"') in vd_body:
    print("VD 段已登记", DET, "跳过")
else:
    # 段内末条锚点
    vd_body_new = vd_body.replace('"details/umich-cse.html"',
                                  '"details/umich-cse.html","' + DET + '"', 1)
    html = html[:vm.start(2)] + vd_body_new + html[vm.end(2):]
    print("VD 段内补登记", DET)

if html != orig:
    open(p, "w", encoding="utf-8").write(html)
    print("写回完成，字节", len(orig.encode("utf-8")), "->", len(html.encode("utf-8")))
else:
    print("无变更")
