# -*- coding: utf-8 -*-
import sys, io, re, os, shutil
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")

TUI = "2026-27 官方口径约 $23,131/年（加州居民）| $38,233/年（非居民/国际生）；职业与自支持学位另计"

TARGETS = {
 "ucla-ms-cs": "details/ucla-ms-computer-science.html",
 "ucla-ece-ms": "details/ucla-ece-ms.html",
 "ucla-mse-ece": "details/ucla-mse-electrical-computer-engineering.html",
 "ucla-ms-me": "details/ucla-ms-mechanical-engineering.html",
 "ucla-aero-ms": "details/ucla-aero-ms.html",
 "ucla-stats-ms": "details/ucla-stats-ms.html",
 "ucla-biostat-ms": "details/ucla-biostat-ms.html",
 "ucla-slavic-ma": "details/ucla-slavic-ma.html",
}

FEE_HTML = ('2026-27 官方口径：多数硕士/博士项目学费与杂费约 <b>$23,131/年</b>（加州居民）、<b>$38,233/年</b>（非居民/国际生）；'
            '职业学位与自支持学位另计，以 Registrar 年度费率表为准。'
            '<a href="https://grad.ucla.edu/funding/tuition/" target="_blank">UCLA Graduate Division 学费页 ↗</a>')

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

# ---- 1. 主记录 tui ----
new_h = h; ok = skip = 0
for pid in TARGETS:
    key = '{id:"%s"' % pid
    p0 = new_h.index(key, i0)
    cand = [x for x in (new_h.find('{id:"', p0+len(key)), new_h.find("const CATD=[", p0)) if x != -1]
    end = min(cand)
    blk = new_h[p0:end]
    m = re.search(r'tui:"([^"]*)"', blk)
    assert m, pid
    if m.group(1) == TUI:
        skip += 1; continue
    new_h = new_h[:p0] + blk[:m.start(1)] + TUI + blk[m.end(1):] + new_h[end:]
    ok += 1
print(f"主页 tui：更新 {ok}，已是 {skip}")
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)
assert cnt == 1440

bak = os.path.join(BASE, "index_main.html.bak_r339")
if not os.path.exists(bak):
    shutil.copy2(IDX, bak); print("备份", os.path.basename(bak))
open(IDX, "w", encoding="utf-8").write(new_h)
print("主文件", os.path.getsize(IDX), "bytes")

# ---- 2. 详情页学费行 ----
okp = 0
for pid, url in TARGETS.items():
    fp = os.path.join(BASE, url.replace("/", os.sep))
    s = open(fp, encoding="utf-8").read()
    if FEE_HTML in s:
        print("  already", pid); okp += 1; continue
    m = re.search(r'(<b>学费：</b>)([\s\S]*?)(</div>)', s)
    if not m:
        print("  !! 未找到学费行", pid); continue
    s2 = s[:m.start(2)] + FEE_HTML + s[m.end(2):]
    # 页脚数据说明
    if "数据说明" not in s2:
        s2 = s2.replace("</body>",
          '<div class="note">📋 数据说明：本页学费口径摘自 UCLA Graduate Division 学费页（实抓 2026-12-02，对应 2026-27 学年）；'
          '官网未公布字段标注待补，不做估算填充。其余字段沿用已核验口径。</div>\n</body>')
    open(fp, "w", encoding="utf-8").write(s2)
    okp += 1
    print("  updated", pid, os.path.getsize(fp))
print("详情页更新:", okp, "/8")
