# -*- coding: utf-8 -*-
"""Round 164 batch: add 5 half-verified MS pages (UIUC ECE / UBC ME / McGill CS Thesis / Princeton CS MSE / MIT MBAn)."""
import os, re

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

# (id, s, n, en, deg, lvl, stem, dur, ddl, lang, test, tui, url, official)
PROGRAMS = [
    ("illinois-ms-ece", "illinois", "电气与计算机工程硕士（研究型 MS）",
     "MS in Electrical and Computer Engineering", "MS", "m", 1,
     "32 credit hours (20 hours 500-level ECE incl. up to 8 hrs ECE 599 thesis; 12 additional hrs); typically 2 years on-campus; Spring admission possible",
     "Fall: January 15 (December 15 for fellowship/award consideration); Spring: September 1",
     "TOEFL/IELTS per Graduate College minimum",
     "GRE: optional (not required); GPA 3.0 minimum (actual admits rarely below 3.5)",
     "Tuition待补 (Graduate College per-credit rate; fellowship/RA/TA available)",
     "details/uiuc-ms-electrical-computer-engineering.html",
     "https://ece.illinois.edu/admissions/graduate/ms-degree-information"),
    ("ubc-meng-mech", "ubc", "机械工程工程硕士（MEng，在校）",
     "Master of Engineering in Mechanical Engineering", "MEng", "m", 1,
     "30 credits; 12 months full-time on-campus (Sept-Aug); 24 credits at 500-level (18 credits in program area incl. project); coursework + capstone project; optional 4-month co-op work term",
     "September 2027 intake: application opens Sep 15 2026, deadline Jan 31 2027 (final document submission Feb 15)",
     "TOEFL/IELTS per UBC Graduate and Postdoctoral Studies minimum",
     "GRE: not required (MEng professional)",
     "International: CAD $27,419.34 first year; Domestic: CAD $6,974.94 first year",
     "details/ubc-meng-mechanical-engineering.html",
     "https://www.grad.ubc.ca/prospective-students/graduate-degree-programs/master-of-engineering-mechanical-engineering"),
    ("mcg-msc-cs-thesis", "mcg", "计算机科学理学硕士（论文型）",
     "M.Sc. in Computer Science (Thesis)", "MSc", "m", 1,
     "45 credits (29 thesis research + 2 seminar + 14 complementary courses at 500/600/700-level); 18-24 months full-time; minimum 3 full-time terms residence; research-oriented entry to PhD or industry research",
     "Fall admission (application opens early; deadline待补)",
     "TOEFL/IELTS per McGill Graduate and Postdoctoral Studies minimum",
     "GRE: not required (MSc Thesis)",
     "Tuition待补 (McGill per-credit rate; research stream typically funded)",
     "details/mcgill-msc-computer-science-thesis.html",
     "https://cs.mcgill.ca/graduate/masters/mscthesis/"),
    ("princeton-cs-mse", "princeton", "计算机科学工程硕士（MSE，论文型）",
     "Master of Science in Engineering (M.S.E.) in Computer Science", "MSE", "m", 1,
     "2 years full-time on-campus; thesis-required track; all admits initially enrolled in M.S.E.; spring of year 1 may switch to M.Eng. non-thesis track; fully funded (TA covering 4 semesters; summer RA at adviser discretion); minimum 4 courses in year 1",
     "Fall admission only; application deadline待补 (Princeton Graduate School standard Dec deadline)",
     "TOEFL/IELTS per Princeton Graduate School minimum",
     "GRE: required (Princeton CS MSE)",
     "Tuition fully covered via TA/RA stipend (no out-of-pocket tuition for admitted MSE students)",
     "details/princeton-cs-mse.html",
     "https://gradschool.princeton.edu/academics/degrees-requirements/fields-study/computer-science"),
    ("mit-mban", "mit", "商业分析硕士（MBAn，STEM）",
     "Master of Business Analytics (MBAn)", "MBAn", "m", 1,
     "12 months full-time on-campus (Fall only; no Spring admission); 111-147 units; team-based curriculum in machine learning, optimization, analytics, organizational dynamics; 7-month Analytics Capstone Project with industry sponsor + full-time summer internship; STEM-designated (24-month OPT extension eligible)",
     "January 5, 2027 (decision March 2027); Fall matriculation only",
     "TOEFL/IELTS per MIT Sloan / MIT Graduate School minimum",
     "GRE/GMAT: required (MBAn); quantitative background required (engineering/math/physics/CS/quant)",
     "Tuition待补 (MIT Sloan MBA-equivalent rate; $22K+ tuition offset via Capstone Project)",
     "details/mit-mban.html",
     "https://mitsloan.mit.edu/master-of-business-analytics"),
]

TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n} | {en} | {s_name}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',sans-serif;max-width:1100px;margin:24px auto;padding:0 20px;color:#222;line-height:1.65}}
h1{{color:#1a3a6c;border-bottom:3px solid #1a3a6c;padding-bottom:10px}}
h2{{color:#1a3a6c;margin-top:28px;border-left:4px solid #1a3a6c;padding-left:10px}}
.grid{{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;margin-top:12px}}
.card{{background:#f5f8fc;border-radius:8px;padding:14px 16px;border-left:3px solid #4a7bb7}}
.card b{{color:#1a3a6c}}
a{{color:#1a6fc2}}
.tag{{display:inline-block;background:#e8f0fb;color:#1a3a6c;padding:2px 8px;border-radius:10px;font-size:12px;margin-right:6px}}
.note{{background:#fff8e6;border-left:3px solid #e0a800;padding:10px 14px;border-radius:4px;margin-top:14px;font-size:14px}}
</style>
</head>
<body>
<h1>{s_name} · {n}</h1>
<p><b>English:</b> {en}<br><b>学位：</b>{deg}　<span class="tag">STEM</span><br><b>官方页面：</b><a href="{official}" target="_blank">{official}</a></p>

<h2>① 项目概览</h2>
<div class="grid">
<div class="card"><b>时长：</b>{dur}</div>
<div class="card"><b>学位类型：</b>{deg}（{lvl_cn}）</div>
<div class="card"><b>授课形式：</b>In-person（全日制在校）</div>
<div class="card"><b>STEM：</b>是</div>
</div>

<h2>② 申请截止与语言</h2>
<div class="grid">
<div class="card"><b>截止日期：</b>{ddl}</div>
<div class="card"><b>语言要求：</b>{lang}</div>
<div class="card"><b>标化要求：</b>{test}</div>
<div class="card"><b>学费：</b>{tui}</div>
</div>

<h2>③ 课程与方向</h2>
<div class="card">{courses}</div>

<h2>④ 申请材料</h2>
<div class="card">{materials}</div>

<h2>⑤ 录取分布</h2>
<div class="card"><i>录取分布，非最低门槛。</i> 官方未公布具体录取 GPA / GRE 中位数值，待系站恢复后补全。</div>

<h2>⑥ 备注</h2>
<div class="note">本页为半核验页：学位、学制、官方链接、申请截止、语言最低分已从学校官网核实；完整课程清单、材料清单、GRE 具体要求、精确学费每学期金额等待系站恢复后补全。</div>

<p style="margin-top:24px"><a href="../index_main.html">← 返回项目库主页</a></p>
</body>
</html>
"""

S_NAME = {
    "illinois": "University of Illinois Urbana-Champaign",
    "ubc": "University of British Columbia",
    "mcg": "McGill University",
    "princeton": "Princeton University",
    "mit": "Massachusetts Institute of Technology",
}
LVL_CN = {"m": "硕士（研究/职业导向）"}

COURSES = {
    "illinois-ms-ece": "32 credit hours; 20 hours must be 500-level ECE (incl. up to 8 hrs ECE 599 thesis). 10 specialization fields: biomedical imaging, microelectronics, quantum electronics, power & energy systems, communications, computer systems, integrated circuits, signal & image processing, control, electromagnetics. Up to 4 hrs of CS 500-level courses may count toward ECE requirement (CS 511/512/522/523/524/525/526/533/538/546/576). Optional Computational Science & Engineering (CSE) and Energy & Sustainability Engineering (EaSE) tracks.",
    "ubc-meng-mech": "30 credits total; 24 credits at 500-level (minimum 18 credits in Mechanical Engineering program area incl. capstone project); max 6 credits at 300/400-level; max 6 credits of 500-level directed studies. Three areas: Mechanical Engineering (general), Mechatronics Design, Naval Architecture & Marine Engineering. 12-month coursework + capstone; optional 4-month co-op work term after course completion.",
    "mcg-msc-cs-thesis": "45 credits total: 29 thesis research (COMP 691/696/697/698/699), 2 seminar (COMP 602/603), 14 complementary at 500/600/700-level (Breadth Requirement). Students must begin in Thesis program; may switch to Non-Thesis after 2nd semester with supervisor approval. Research areas: algorithms, AI, bioinformatics, ML, systems, theory, HCI. Fast-track to PhD available after 2-4 full-time semesters.",
    "princeton-cs-mse": "2 years full-time; thesis-required track. All admits initially enrolled in M.S.E.; spring of year 1 may switch to M.Eng. (non-thesis, coursework-only). Minimum 4 courses in year 1. Fully funded: TA covering 4 semesters; summer RA at adviser discretion. Research areas: algorithms, computational biology, machine learning, programming languages, security, systems, theory, visualization. Students wishing to continue to PhD apply during fall of 2nd year via normal process.",
    "mit-mban": "111-147 units across Fall, IAP, Spring, Summer. Fall core: Machine Learning (12), Intensive Hands-on Deep Learning (6), Optimization, Analytics, Organizational Dynamics, technical tools + 1 unrestricted elective. Optional electives from MIT Operations Research Center (ORC). 7-month Analytics Capstone: team of 2 + industry sponsor; Feb-May on campus at MIT; Summer full-time on-site internship at host org; August final report & presentation. STEM-designated (24-month OPT extension eligible).",
}

MATERIALS = {
    "illinois-ms-ece": "Graduate College online application; transcripts; 3 letters of recommendation; statement of purpose; CV; TOEFL/IELTS; GRE optional. 完整材料清单待系站恢复后补全。",
    "ubc-meng-mech": "UBC Graduate Studies online application; transcripts; 2-3 letters; statement of intent; CV; TOEFL/IELTS; relevant prior education in mechanical engineering. 完整材料清单待补全。",
    "mcg-msc-cs-thesis": "McGill Graduate and Postdoctoral Studies application; transcripts; 3 letters; statement of research interest; CV; TOEFL/IELTS; supervisor identification preferred. 完整材料清单待补全。",
    "princeton-cs-mse": "Princeton Graduate School application; transcripts; 3 letters; statement of purpose; CV; TOEFL/IELTS; GRE required; application fee $75. 完整材料清单待补全。",
    "mit-mban": "MIT Sloan application; transcripts; 2 essays; 1-2 letters; resume; TOEFL/IELTS; GRE/GMAT required; video interview. 完整材料清单待补全。",
}

html = open(IDX, encoding="utf-8").read()
orig_len = len(html)

# 1. Generate 5 detail pages
for (pid, s, n, en, deg, lvl, stem, dur, ddl, lang, test, tui, url, official) in PROGRAMS:
    page = TEMPLATE.format(
        s_name=S_NAME[s], n=n, en=en, deg=deg, lvl_cn=LVL_CN[lvl],
        dur=dur, ddl=ddl, lang=lang, test=test, tui=tui,
        courses=COURSES[pid], materials=MATERIALS[pid], official=official,
    )
    p = os.path.join(ROOT, url)
    open(p, "w", encoding="utf-8").write(page)
    print(f"[OK] generated: {url} ({len(page)} chars)")

# 2. Append to PROGRAMS array (brace-depth match end of ])
def find_array_end(html, start_marker):
    i = html.find(start_marker)
    if i < 0:
        raise RuntimeError("marker not found: " + start_marker)
    j = html.find("[", i)
    depth = 1
    k = j + 1
    while k < len(html) and depth > 0:
        c = html[k]
        if c == "[":
            depth += 1
        elif c == "]":
            depth -= 1
        k += 1
    return k - 1

new_entries = []
for (pid, s, n, en, deg, lvl, stem, dur, ddl, lang, test, tui, url, official) in PROGRAMS:
    entry = (f'{{id:"{pid}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
             f'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test}"}},tui:"{tui}",url:"{url}"}}')
    new_entries.append(entry)

end = find_array_end(html, "const PROGRAMS=")
prefix = html[:end].rstrip()
if prefix.endswith("}"):
    insert_text = ",\n" + ",\n".join(new_entries) + "\n"
elif prefix.endswith(","):
    insert_text = "\n" + ",\n".join(new_entries) + "\n"
else:
    insert_text = ",\n" + ",\n".join(new_entries) + "\n"
html = html[:end] + insert_text + html[end:]
print(f"[OK] PROGRAMS appended {len(new_entries)}")

# 3. Append to VERIFIED_DETAILS set — use url field (index 12) directly
vd_new = [prog[12] for prog in PROGRAMS]
vd_marker = "const VERIFIED_DETAILS=new Set("
i = html.find(vd_marker)
if i < 0:
    raise RuntimeError("VD marker not found")
j = html.find("(", i)
depth = 1
k = j + 1
while k < len(html) and depth > 0:
    c = html[k]
    if c == "(":
        depth += 1
    elif c == ")":
        depth -= 1
    k += 1
end = k - 1
prefix = html[:end].rstrip()
if prefix.endswith('"'):
    insert_text = "," + ",".join(f'"{u}"' for u in vd_new)
elif prefix.endswith(","):
    insert_text = ",".join(f'"{u}"' for u in vd_new)
else:
    insert_text = ",".join(f'"{u}"' for u in vd_new)
html = html[:end] + insert_text + html[end:]
print(f"[OK] VERIFIED_DETAILS appended {len(vd_new)} urls: {vd_new}")

open(IDX, "w", encoding="utf-8").write(html)
print(f"[DONE] index_main.html written back ({len(html)} chars, was {orig_len})")
