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

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/季度，"
             "首次入学一次性注册服务费 $115，国际新生一次性签证管理费 $200。"
             "<a href=\"https://students.ucsd.edu/finances/fees/registration/2026-27/graduate.html\" target=\"_blank\">"
             "UCSD 2026-27 研究生注册费官方页 ↗</a>（核对 2026-12-02）")

SS_TUI = "$1,056/学分 × 55 学分 ≈ $58,080 ＋ 校园费 $9,263/年（2026-27 自支持费率）"
SS_DETAIL = ("self-supporting 自支持项目按学分计费：<b>2026 秋季入学 $1,056/学分</b>（4 学分单课 $4,224），"
             "本项目管理页载明 55 学分，按此计学费约 <b>$58,080</b>；另按季收取校园费，年度合计 <b>$9,263.17</b>"
             "（含学生服务费、健保 $2,220/季等，不含学分学费）。"
             "<a href=\"https://students.ucsd.edu/finances/fees/registration/2026-27/self-supporting.html\" target=\"_blank\">"
             "UCSD 2026-27 自支持项目费率页 ↗</a>（核对 2026-12-02）")

ITEMS = [("ucsd-ece-am-ms", AC_TUI, AC_DETAIL), ("ucsd-csme-ms", AC_TUI, AC_DETAIL),
         ("ucsd-css-ms", SS_TUI, SS_DETAIL)]

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

for pid, tui, _ in ITEMS:
    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)
    s = s[:a] + blk[:m.start()] + 'tui:"' + tui + '"' + blk[m.end():] + s[nxt:]
    print("tui", pid, "|", old[:26], "->", tui[:26])
open(IDX, "w", encoding="utf-8").write(s)

PATS = [
    (r'(<b>Tuition:</b><br>)([\s\S]*?)(</div>)', "A"),
    (r'(<span class="label">学费</span><span class="value">)([\s\S]*?)(</span>)', "B"),
    (r'(<h3>学费与资助</h3>\s*<p>)([\s\S]*?)(</p>)', "C"),
]
ok = 0
for pid, _, det in ITEMS:
    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 "1,056" in t or "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)] + det + t[m.end(2):]
            done = True; print(" patched", tag, pid); break
    if not done:
        print("!! 未匹配", pid); continue
    if "数据说明" not in t and "</body>" in t:
        t = t.replace("</body>", '<div class="note">📋 数据说明：费用口径摘自 UC San Diego Students·Finances·Fees 2026–27 官方页（实抓 2026-12-02）；'
                      '州资助学术型项目适用统一注册费表，self-supporting 项目按学分另计。官网未公布字段标待补，不做估算。</div>\n</body>')
    open(fp, "w", encoding="utf-8").write(t)
    ok += 1
print("详情页同步:", ok, "/3")
