# -*- 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")

# —— 官方口径（https://students.ucsd.edu/finances/fees/registration/2026-27/graduate.html，Last Updated 2026-09-20）——
AC_TUI = "$22,985/年（加州居民）· $38,087/年（非居民/国际生）· 2026-27 含强制健保"
AC_DETAIL = ("2026-27 学年注册费合计 <b>$22,985.17/年</b>（加州居民）／<b>$38,087.17/年</b>（非居民·国际生）；"
             "构成：学费 $4,574/季度、学生服务费 $448/季度、非居民附加学费（NRST）$5,034/季度、"
             "强制学生健保 SHIP $2,220/季度、校园费合计约 $382/季度，另首次入学一次性注册服务费 $115；"
             "国际新生一次性签证管理费 $200。"
             "<a href=\"https://students.ucsd.edu/finances/fees/registration/2026-27/graduate.html\" target=\"_blank\">"
             "UCSD 2026-27 研究生注册费官方页 ↗</a>（核对日期 2026-12-02）")

EIGHT = ["ucsd-cse-ms","ucsd-mae-ms","ucsd-se-ms","ucsd-math-app-ms",
         "ucsd-bioe-med-ms","ucsd-es-bb-ms","ucsd-es-pe-ms","ucsd-es-cm-ms"]

s = open(IDX, encoding="utf-8").read()
shutil.copy2(IDX, IDX + ".bak_r340")

# ---------- 1. 主页面 tui 定向替换 ----------
for pid in EIGHT:
    key = '{id:"%s"' % pid
    a = s.find(key)
    if a < 0:
        print("!! 主记录缺失", pid); continue
    nxt = s.find('{id:"', a + 5)
    blk = s[a:nxt]
    m = re.search(r'tui:"([^"]*)"', blk)
    if not m:
        print("!! 无 tui 字段", pid); continue
    old = m.group(1)
    newblk = blk[:m.start()] + 'tui:"' + AC_TUI + '"' + blk[m.end():]
    s = s[:a] + newblk + s[nxt:]
    print("tui", pid, "|", old[:30], "->", AC_TUI[:24])
open(IDX, "w", encoding="utf-8").write(s)

# ---------- 2. 详情页同步 ----------
PATS = [
    (r'(<b>Tuition:</b><br>)([\s\S]*?)(</div>)', "A"),
    (r'(<span class="label">学费</span><span class="value">)([\s\S]*?)(</span>)', "B"),
]
FOOT = ('<div class="note">📋 数据说明：费用口径摘自 UC San Diego Students·Finances·Fees 2026–27 研究生注册费页'
        '（实抓 2026-12-02，官方页 Last Updated 2026-09-20）；州资助学术型项目适用该校统一注册费表，'
        'self-supporting（MAS/MDSO/MPH/MS/MSDDPM）、GPS、Rady、医学院、药学院另表计费。官网未公布字段标待补，不做估算。</div>')

ok = 0
for pid in EIGHT:
    fp = os.path.join(BASE, "details", pid + ".html")
    if not os.path.exists(fp):
        print("!! 无详情页", pid); continue
    t = open(fp, encoding="utf-8").read()
    if "22,985" in t:
        print("already", pid); ok += 1; continue
    done = False
    for p, tag in PATS:
        m = re.search(p, t)
        if m:
            t = t[:m.start(2)] + AC_DETAIL + t[m.end(2):]
            done = True; print("  patched", tag, pid); break
    if not done and pid == "ucsd-cse-ms":
        # 卡片网格页：新增“学费”卡并修正半核验页说明
        anchor = '<div class="card"><h3>Thesis</h3>'
        if anchor in t:
            t = t.replace(anchor,
                '<div class="card"><h3>学费（2026-27）</h3><div class="v">$22,985.17/年（加州居民）<br>'
                '$38,087.17/年（非居民·国际生）<br>含学费 $4,574/季 + 健保 $2,220/季</div></div>\n' + anchor, 1)
            done = True; print("  card inserted", pid)
        t = t.replace("、精确学费、语言最低分待系站目录恢复后补全", "、语言最低分待研究生院统一口径页面恢复后补全。学费已按 2026-27 研究生注册费官方页回填")
    if not done:
        print("!! 未匹配", pid); continue
    if "数据说明" not in t and "</body>" in t:
        t = t.replace("</body>", FOOT + "\n</body>")
    open(fp, "w", encoding="utf-8").write(t)
    ok += 1
    print("  size", os.path.getsize(fp))
print("详情页同步:", ok, "/8")
