# -*- coding: utf-8 -*-
import sys, io, re, os, shutil, datetime
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')

BASE = r"D:\work buddy\2026-11-05-14-15-52"
IDX = os.path.join(BASE, "index_main.html")

# ---------- 1. 主记录 tui 回填 ----------
FEE_MENG = "2026-27 官方费率：非居民/国际生 $37,002.25/学期（新生，含一次性文档费 $119）；居民 $29,886.75/学期（Registrar 2026-27 · College of Engineering 全部 M.Eng）；按学期计费"
FEE_MIMS = "2026-27 官方费率：非居民/国际生 $23,715.25/学期（新生，含一次性文档费 $119）；居民 $17,592.75/学期（Registrar 2026-27 · School of Information MIMS）；按学期计费"

TARGETS = {
 "berkeley-meng-eecs": FEE_MENG,
 "berkeley-meng-me": FEE_MENG,
 "berkeley-meng-ieor": FEE_MENG,
 "berkeley-meng-bioe": FEE_MENG,
 "berkeley-meng-cee": FEE_MENG,
 "berkeley-meng-mse": FEE_MENG,
 "berkeley-meng-ne": FEE_MENG,
 "berkeley-mims": FEE_MIMS,
}

h = open(IDX, encoding="utf-8").read()
assert "const PROGRAMS=[" in h and "const CATD=[" in h
i = h.index("const PROGRAMS=["); j = h.index("const CATD=[", i)

new_h = h
ok, skip = 0, 0
for pid, fee in TARGETS.items():
    key = '{id:"%s"' % pid
    p0 = new_h.index(key, i)
    p1 = new_h.find('{id:"', p0 + len(key))
    p2 = new_h.find("const CATD=[", p0)
    end = min([x for x in (p1, p2) if x != -1])
    blk = new_h[p0:end]
    m = re.search(r'tui:"([^"]*)"', blk)
    assert m, f"tui not found in {pid}"
    if m.group(1) == fee:
        skip += 1
        continue
    nb = blk[:m.start(1)] + fee + blk[m.end(1):]
    new_h = new_h[:p0] + nb + new_h[end:]
    ok += 1

print(f"tui 回填：更新 {ok} 条，已是最新 {skip} 条")
assert ok + skip == 8, "target count mismatch"
assert "}{" not in new_h, "出现 }{ 缺逗号"

# 计数校验
cnt = len(re.findall(r'\{id:"', new_h[new_h.index("const PROGRAMS=["):new_h.index("const CATD=[")]))
print("PROGRAMS 计数:", cnt)

bak = os.path.join(BASE, "index_main.html.bak_r338")
if not os.path.exists(bak):
    shutil.copy2(IDX, bak)
    print("备份:", bak)

open(IDX, "w", encoding="utf-8").write(new_h)
print("主文件已写入，bytes:", os.path.getsize(IDX))
