import re, os, sys, io, json
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")
r = open(fp, encoding="utf-8").read()

# 断言声明行无空格
assert "const PROGRAMS=[" in r, "PROGRAMS 声明行异常"
assert "const CATD=[" in r, "CATD 声明行异常"

FILL = {
 "cmu-msin": "GRE 不要求（Fall 2027 不索取、不审阅；未来学期或调整）",
 "cmu-msis": "GRE 不要求（Fall 2027 不索取、不审阅；未来学期或调整）",
 "duke-aipi": "GRE 可选（2027 申请季；录取分布，非最低门槛）",
 "cmu-msm-ms": "GMAT/GRE/EA 其一 required（可申请 waiver，须具突出量化课程；人文社科背景不符合 waiver 条件）",
 "uw-mdsai-coop": "GRE 不要求（数据科学项目）",
 "geo-bioinfo-ms": "GRE 不要求、不用于录取",
}

seg_m = re.search(r'(const PROGRAMS\s*=\s*\[\n?)([\s\S]*?)(\n?\];)', r)
seg = seg_m.group(2)

def repl_block(m):
    bid = m.group(1); body = m.group(2)
    if bid not in FILL:
        return m.group(0)
    cls_m = re.search(r'test:\{cls:"([^"]*)"\}', body)
    if not cls_m:
        print(f"[WARN] {bid} 未定位 test.cls 结构，跳过")
        return m.group(0)
    if cls_m.group(1).strip():
        print(f"[SKIP] {bid} cls 已有值: {cls_m.group(1)[:40]}")
        return m.group(0)
    new_body = body.replace(f'test:{{cls:"{cls_m.group(1)}"}}',
                            f'test:{{cls:"{FILL[bid]}"}}', 1)
    print(f"[OK] {bid} -> {FILL[bid][:50]}")
    return "{id:\""+bid+"\""+new_body

new_seg = re.sub(r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|$)', repl_block, seg)
r2 = r[:seg_m.start(2)] + new_seg + r[seg_m.end(2):]

# 校验：6 条新值都在
for bid, val in FILL.items():
    assert val in r2, f"{bid} 回填未生效"
# 校验无 }{ 缺逗号（粗查）
bad = len(re.findall(r'\}\{', r2))
print("缺逗号 }{ 计数:", bad)

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