# -*- coding: utf-8 -*-
import io, sys, os, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
os.chdir(r"D:\work buddy\2026-11-05-14-15-52")
IDX = "index_main.html"
idx = open(IDX, encoding="utf-8").read()

new_entries = [
    dict(id="ut-ce-masc", s="ut", n="土木与矿物工程应用科学硕士（MASc）", en="Master of Applied Science in Civil & Mineral Engineering", dept="Department of Civil & Mineral Engineering", college="Faculty of Applied Science and Engineering", disc="eng", deg="MASc", dur="研究型硕士（导师录取前由研院分配）", stem=0, test="notreq", ddl="待补（链接至系站）", lang="待补（IELTS/TOEFL 最低分）", tui="打包学费待补", url="details/ut-c5c7562.html"),
    dict(id="ut-bmc-msc", s="ut", n="生物医学传播理学硕士（MScBMC）", en="Master of Science in Biomedical Communications", dept="Biomedical Communications Program", college="Faculty of Medicine", disc="med", deg="MScBMC", dur="授课型专业硕士（医学插画/医学传播）", stem=0, test="notreq", ddl="待补（链接至系站）", lang="TOEFL iBT 100（写作口语25）/ IELTS 7.5（单项6.5）/ COPE 86", tui="打包学费待补", url="details/ut-c027862.html"),
    dict(id="ut-pharm-msc", s="ut", n="药学科学理学硕士（MSc）", en="Master of Science in Pharmaceutical Sciences", dept="Leslie Dan Faculty of Pharmacy", college="University of Toronto", disc="med", deg="MSc", dur="研究型硕士（须自行联系导师）", stem=0, test="notreq", ddl="待补（链接至系站）", lang="待补（ELP 最低分）", tui="打包学费待补", url="details/ut-pharm-sci-msc.html"),
    dict(id="ut-mpp", s="ut", n="公共政策硕士（MPP）", en="Master of Public Policy", dept="Munk School of Global Affairs & Public Policy", college="University of Toronto", disc="soc", deg="MPP", dur="授课型专业硕士", stem=0, test="rec", ddl="Fall 2025：2025-01-27（2027 待更新）", lang="待补（IELTS/TOEFL 最低分）", tui="打包学费待补", url="details/ut-c607d7e.html"),
    dict(id="ut-mi", s="ut", n="信息学硕士（MI）", en="Master of Information", dept="Faculty of Information", college="University of Toronto", disc="cs", deg="MI", dur="专业型硕士（PhD 双轨）", stem=0, test="notreq", ddl="待补（链接至系站）", lang="待补（IELTS/TOEFL 最低分）", tui="打包学费待补", url="details/ut-c142af9.html"),
]

prog_seg = idx[idx.find("const PROGRAMS="):idx.find("const CATD=")]

def entry_str(e):
    stem = "1" if e["stem"] else "0"
    return ('{id:"' + e["id"] + '",s:"' + e["s"] + '",n:"' + e["n"] + '",en:"' + e["en"] + '",dept:"' + e["dept"] + '",college:"' + e["college"] + '",'
     'disc:"' + e["disc"] + '",lvl:"m",deg:"' + e["deg"] + '",dur:"' + e["dur"] + '",stem:' + stem + ',rank:"",'
     'test:{cls:"' + e["test"] + '"},ddl:"' + e["ddl"] + '",lang:"' + e["lang"] + '",tui:"' + e["tui"] + '",url:"' + e["url"] + '"},')

anchor = '{id:"ut-mengcem",s:"ut"'
anchor_pos = idx.find(anchor)
assert anchor_pos > 0, "末条锚点未找到"
line_end = idx.find("\n", anchor_pos)
to_add = [e for e in new_entries if ('{id:"' + e["id"] + '"') not in prog_seg]
if to_add:
    block = "\n" + "\n".join(entry_str(e) for e in to_add)
    idx = idx[:line_end] + block + idx[line_end:]
    print("PROGRAMS 追加", len(to_add), "条：", [e["id"] for e in to_add])
else:
    print("PROGRAMS 无新增")

vd_m = re.search(r'(const VERIFIED_DETAILS=new Set\(\[)(.*?)(\]\);)', idx, re.S)
assert vd_m, "VD 段未找到"
vd_body = vd_m.group(2)
vd_list = re.findall(r'"([^"]+)"', vd_body)
all_det = [e["url"] for e in new_entries]
new_det = [d for d in all_det if d not in vd_list]
if new_det:
    add_str = ",".join('"' + d + '"' for d in new_det)
    new_vd_body = vd_body.rstrip()
    if not new_vd_body.endswith(","):
        new_vd_body = new_vd_body + ","
    new_vd_body = new_vd_body + add_str
    idx = idx[:vd_m.start(2)] + new_vd_body + idx[vd_m.end(2):]
    print("VD 登记", len(new_det), "条：", new_det)
else:
    print("VD 无新增")

# 补 CATD 缺失条目（仅 Pharmaceutical Sciences 新建 det）
catd_start = idx.find("const CATD=")
catd_end = idx.find("const VERIFIED_DETAILS=")
catd_seg = idx[catd_start:catd_end]
catd_add = []
for e in new_entries:
    if e["url"] not in catd_seg:
        # CATD 格式: ["ut","学院","英文名","中文名","学位","官网URL","disc","det"]
        cn = e["n"]
        row = '["ut", "' + e["college"] + '", "' + e["en"] + '", "' + cn + '", "' + e["deg"] + '", "https://www.sgs.utoronto.ca/programs/' + e["id"].replace("ut-","").replace("-masc","").replace("-msc","").replace("-mpp","").replace("-mi","") + '/", "' + e["disc"] + '", "' + e["url"] + '"],'
        catd_add.append(row)
if catd_add:
    # 找 CATD 段末条（最后一个 ], 后的 ];）
    last_close = catd_seg.rfind("];")
    if last_close > 0:
        abs_pos = catd_start + last_close
        block = "\n" + "\n".join(catd_add)
        idx = idx[:abs_pos] + block + "\n" + idx[abs_pos:]
        print("CATD 补", len(catd_add), "条：", [e["id"] for e in new_entries if e["url"] not in catd_seg])

open(IDX, "w", encoding="utf-8").write(idx)
print("写回完成，字符", len(idx))
