# -*- coding: utf-8 -*-
"""Round 182: Add 5 McGill/Emory/UBC thesis-based master's programs."""
import os, re, json

BASE = r"D:\work buddy\2026-11-05-14-15-52"
DETAILS = os.path.join(BASE, "details")

# ---------- 5 programs metadata ----------
programs = [
    {
        "id": "mcg-msc-ece",
        "s": "mcg",
        "n": "电子与计算机工程理学硕士（论文型）",
        "en": "M.Sc. in Electrical and Computer Engineering (Thesis)",
        "deg": "MSc",
        "lvl": "m",
        "stem": 1,
        "dur": "18-36 months full-time (46 credits)",
        "ddl": "2027-01-15 (Fall admission; Sept start only)",
        "lang": "TOEFL iBT 92 (min 20 each) / IELTS 6.5",
        "test": {"cls": "GRE not mandatory (optional)"},
        "tui": "CAD 8,000-10,000/year (Quebec resident rate; international ~CAD 18,000-22,000)",
        "url": "details/mcg-msc-ece.html",
        "school": "McGill University",
        "college": "Faculty of Engineering, Dept of ECE",
        "rank": "Top 1 engineering school in Canada; research thesis-based",
        "website": "https://www.mcgill.ca/ece/graduate/graduate/process",
        "bulletin": "https://coursecatalogue.mcgill.ca/en/graduate/engineering/electrical-computer-engineering/",
        "bg": "Quebec, Montreal; bilingual (English/Friendly French)",
        "career": "Research/PhD track; VLSI, communications, photonics, robotics, ML, bioinformatics",
        "gpa": "CGPA 3.0/4.0 or 3.2/4.0 last two years; ECE undergrad or related",
        "materials": "Transcripts, 2 reference letters, CV, personal statement; application fee CAD 139.63",
        "credits": "46 credits (thesis-based): graduate coursework + research thesis",
    },
    {
        "id": "mcg-msc-me",
        "s": "mcg",
        "n": "机械工程理学硕士（论文型）",
        "en": "M.Sc. in Mechanical Engineering (Thesis)",
        "deg": "MSc",
        "lvl": "m",
        "stem": 1,
        "dur": "18-24 months full-time (45 credits)",
        "ddl": "2027-01-15 (Fall admission)",
        "lang": "TOEFL iBT 92 (min 20 each) / IELTS 7.0",
        "test": {"cls": "GRE not required"},
        "tui": "CAD 8,000-10,000/year (Quebec resident; international ~CAD 18,000-22,000)",
        "url": "details/mcg-msc-me.html",
        "school": "McGill University",
        "college": "Faculty of Engineering, Dept of Mechanical Engineering",
        "rank": "Top mechanical engineering in Canada; thesis research",
        "website": "https://www.mcgill.ca/mecheng/grad/admission",
        "bulletin": "https://coursecatalogue.mcgill.ca/en/graduate/engineering/mechanical-engineering/",
        "bg": "Quebec, Montreal",
        "career": "Research/PhD track; fluid mechanics, materials, biomechanics, aerospace, robotics, energy",
        "gpa": "CGPA 3.3/4.0; Engineering or Physical/Math/CS undergrad",
        "materials": "Transcripts, 2 reference letters, CV, 1-page personal statement; application fee CAD 139.63",
        "credits": "45 credits: 28 thesis + 16 coursework + 1 seminar",
    },
    {
        "id": "mcg-msc-math",
        "s": "mcg",
        "n": "数学与统计学理学硕士（论文型）",
        "en": "M.Sc. in Mathematics and Statistics (Thesis)",
        "deg": "MSc",
        "lvl": "m",
        "stem": 1,
        "dur": "24 months full-time",
        "ddl": "2027-01-15 (Fall); 2026-07-15 (Winter, international)",
        "lang": "TOEFL iBT 92 / IELTS 6.5",
        "test": {"cls": "GRE optional (if available)"},
        "tui": "CAD 8,000-10,000/year (Quebec resident; international ~CAD 18,000-22,000)",
        "url": "details/mcg-msc-math.html",
        "school": "McGill University",
        "college": "Faculty of Science, Dept of Mathematics and Statistics",
        "rank": "Top math/stats department in Canada; funded thesis-based",
        "website": "https://www.mcgill.ca/mathstat/graduate",
        "bulletin": "https://www.mcgill.ca/gradapplicants/programs/mathematics-and-statistics",
        "bg": "Quebec, Montreal",
        "career": "PhD track; pure math, applied math, statistics, combinatorics, financial math",
        "gpa": "CGPA 3.0/4.0; honours degree in math or closely related field",
        "materials": "Transcripts, 2 reference letters, personal statement, research proposal (optional); application fee CAD 139.63",
        "credits": "Thesis-based program; coursework + research thesis",
    },
    {
        "id": "emory-msph-biostat",
        "s": "emory",
        "n": "生物统计公共卫生理学硕士（研究型）",
        "en": "MSPH in Biostatistics",
        "deg": "MSPH",
        "lvl": "m",
        "stem": 1,
        "dur": "2 years full-time (48 credit hours)",
        "ddl": "2026-12-01 (Fall 2027 admission via SOPHAS)",
        "lang": "TOEFL iBT 79-80 / IELTS 6.0",
        "test": {"cls": "GRE optional (not required for 2027 cycle)"},
        "tui": "~$23,000/semester (estimated; Rollins tuition per credit hour)",
        "url": "details/emory-msph-biostat.html",
        "school": "Emory University",
        "college": "Rollins School of Public Health, Dept of Biostatistics and Bioinformatics",
        "rank": "Top 5 public health school in US; research-oriented biostatistics",
        "website": "https://sph.emory.edu/degrees-programs/msph/biostatistics",
        "bulletin": "https://sph.emory.edu/admissions/how-to-apply/masters-programs",
        "bg": "Atlanta, Georgia, USA; CDC headquarters adjacent",
        "career": "Biostatistician in pharma, CDC, NIH, research; PhD prep track",
        "gpa": "3.0+ preferred; must complete multivariate calculus (Calc III) B+ and linear algebra B+",
        "materials": "SOPHAS application, transcripts, 2 recommendation letters, personal statement, CV; WES for non-US transcripts",
        "credits": "48 credit hours including applied practicum + integrative learning experience",
    },
    {
        "id": "ubc-msc-cs-essay",
        "s": "ubc",
        "n": "计算机科学理学硕士（论文/短文型）",
        "en": "M.Sc. in Computer Science (Thesis / Essay options)",
        "deg": "MSc",
        "lvl": "m",
        "stem": 1,
        "dur": "24 months full-time",
        "ddl": "2026-12-15 (September 2027 admission)",
        "lang": "TOEFL iBT 92 (min 22 W/R, 21 L/S) / IELTS 6.5",
        "test": {"cls": "GRE not required"},
        "tui": "CAD 8,000-10,000/year (Canadian; international ~CAD 18,000-22,000)",
        "url": "details/ubc-msc-cs-essay.html",
        "school": "University of British Columbia",
        "college": "Faculty of Science, Dept of Computer Science",
        "rank": "Top CS department in Canada; three MSc options available",
        "website": "https://www.cs.ubc.ca/students/grad/admissions",
        "bulletin": "https://vancouver.calendar.ubc.ca/faculties-colleges-and-schools/faculty-graduate-and-postdoctoral-studies/degree-programs/computer-science",
        "bg": "Vancouver, British Columbia, Canada; coastal tech hub",
        "career": "PhD track or industry R&D; ML, NLP, computer vision, systems, HCI, graphics",
        "gpa": "B+ (76%) average in third/fourth-year CS courses; 4-year bachelor's in CS or related",
        "materials": "Online application, 3 reference letters, statement of interest, CV, transcripts; application fee CAD 110",
        "credits": "3 options: 18 coursework + 12 thesis / 24 coursework + 6 thesis / 27 coursework + 3 essay",
    },
]

# ---------- Generate detail pages ----------
def gen_html(p):
    stem_badge = "STEM · OPT 36 months" if p["stem"] else "Not STEM"
    return f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{p['en']} · {p['school']} · 项目详情</title>
<style>
:root{{--navy1:#0b2447;--navy2:#19376d;--navy3:#2b5ba8;--gold:#f0a500;--bg:#f5f7fa;--card:#fff;--line:#e3e8f0;--text:#1f2937;--muted:#6b7280;--blue:#2563eb}}
*{{margin:0;padding:0;box-sizing:border-box}}
body{{font-family:"PingFang SC","Microsoft YaHei","Segoe UI",sans-serif;background:var(--bg);color:var(--text);font-size:14px}}
a{{color:var(--blue)}}
.hero{{background:linear-gradient(135deg,var(--navy1) 0%,var(--navy2) 55%,var(--navy3) 100%);color:#fff;padding:24px 30px 20px}}
.hero h1{{font-size:21px}}
.hero .en{{font-size:13px;opacity:.85;margin-top:4px}}
.hero .school{{margin-top:8px;font-size:14px;font-weight:600;color:#ffd77a}}
.badges{{margin-top:12px;display:flex;gap:8px;flex-wrap:wrap}}
.badge{{font-size:12px;border-radius:5px;padding:3px 10px;font-weight:700;background:rgba(240,165,0,.25);color:#ffe1a1}}
.wrap{{max-width:900px;margin:20px auto 60px;padding:0 16px}}
.back{{display:inline-block;margin-bottom:14px;color:var(--navy2);text-decoration:none;font-size:13px;font-weight:600}}
.card{{background:var(--card);border-radius:12px;box-shadow:0 2px 10px rgba(15,35,80,.08);border:1px solid var(--line);padding:20px 24px;margin-bottom:16px}}
.card h2{{font-size:16px;color:var(--navy2);border-left:4px solid var(--gold);padding-left:10px;margin-bottom:14px}}
table.kv{{width:100%;border-collapse:collapse;font-size:13px}}
table.kv td{{border:1px solid var(--line);padding:10px 12px;vertical-align:top}}
table.kv td.k{{width:130px;background:#f0f4fa;color:var(--muted);font-weight:600;white-space:nowrap}}
table.kv td.v{{line-height:1.8}}
ul.cl{{padding-left:20px;line-height:1.95;font-size:13px}}
ul.cl li{{margin-bottom:9px}}
ul.cl li b{{color:var(--navy2)}}
.note{{font-size:12px;color:var(--muted);margin-top:10px;line-height:1.7}}
.clinks{{margin-top:14px;padding-top:12px;border-top:1px dashed var(--line);display:flex;gap:8px;flex-wrap:wrap}}
.clinks a{{font-size:12px;padding:6px 12px;background:#eef3fb;color:var(--navy2);border:1px solid #cfdcef;border-radius:7px;text-decoration:none;font-weight:600}}
.links a{{display:inline-block;margin:4px 8px 4px 0;padding:8px 14px;background:var(--navy2);color:#fff;border-radius:8px;font-size:13px;text-decoration:none;font-weight:600}}
.foot{{max-width:900px;margin:0 auto 40px;padding:0 16px}}
.yellow{{background:#fff8e1;border-left:4px solid var(--gold);border-radius:8px;padding:12px 16px;font-size:12px;line-height:1.8}}
</style>
</head>
<body>
<div class="hero">
  <h1>{p['n']}</h1>
  <div class="en">{p['en']}</div>
  <div class="school">{p['school']} · {p['college']}</div>
  <div class="badges"><span class="badge">{stem_badge}</span></div>
</div>
<div class="wrap">
  <a class="back" href="../index_main.html">← 返回项目库</a>
<div class="card"><h2>申请要求（2027 申请季 · 官网口径）</h2>
<table class="kv">
<tr><td class="k">申请截止</td><td class="v"><b>{p['ddl']}</b></td></tr>
<tr><td class="k">语言要求</td><td class="v">{p['lang']}</td></tr>
<tr><td class="k">标化要求</td><td class="v">{p['test']['cls']}</td></tr>
<tr><td class="k">学术背景</td><td class="v">{p['gpa']}</td></tr>
<tr><td class="k">申请材料</td><td class="v">{p['materials']}</td></tr>
</table>
<div class="clinks"><a href="{p['website']}" target="_blank">📘 项目官方页 ↗</a><a href="{p['bulletin']}" target="_blank">📘 官方目录/公告 ↗</a></div>
</div>
<div class="card"><h2>费用（官网口径）</h2>
<table class="kv">
<tr><td class="k">学费</td><td class="v">{p['tui']}</td></tr>
</table>
<div class="note">⚠️ 学费为官网公布或近似区间，精确金额以学校账单为准；国际生学费通常高于本地生。</div>
</div>
<div class="card"><h2>课程设置与学位要求</h2>
<ul class="cl">
<li><b>学位总要求</b>：{p['credits']}</li>
<li><b>项目方向</b>：{p['career']}</li>
<li><b>学制</b>：{p['dur']}</li>
</ul>
<div class="note">📋 课程设置详细列表官网未完整公开，待后续补核；本页为半核验页。</div>
</div>
<div class="card"><h2>培养方案与项目要点</h2>
<div style="font-size:13px;line-height:1.9">
{p['rank']}。{p['bg']}。
<div class="note">来源：{p['school']} 官网（抓取日期 2026-11-26）。官网未公布的字段整项不展示，不做估算填充。</div>
</div>
</div>
<div class="card"><h2>院校与城市速览（编辑整理）</h2>
<table class="kv">
<tr><td class="k">📍 位置</td><td class="v">{p['bg']}</td></tr>
<tr><td class="k">💼 就业方向</td><td class="v">{p['career']}</td></tr>
</table>
<div class="note">ℹ️ 本卡为编辑整理内容，便于接待沟通；上方各卡为官网数据。</div>
</div>
<div class="card links"><h2>官方链接</h2>
<a href="{p['website']}" target="_blank">🔗 项目官方页面</a>
<a href="{p['bulletin']}" target="_blank">🔗 官方目录 / 公告</a>
</div>
</div>
<div class="foot">
  <div class="yellow">📋 数据说明：本页内容摘自 {p['school']} 官网（抓取日期 2026-11-26，对应 2027 申请季）。官网未公布的字段整项不展示，不做估算填充。录取分数为录取分布参考，非最低门槛。</div>
</div>
</body>
</html>
"""

for p in programs:
    path = os.path.join(DETAILS, p["id"] + ".html")
    with open(path, "w", encoding="utf-8") as f:
        f.write(gen_html(p))
    print("Wrote:", path)

# ---------- Append to PROGRAMS ----------
idx_path = os.path.join(BASE, "index_main.html")
h = open(idx_path, "r", encoding="utf-8").read()

# Find PROGRAMS array end using bracket depth
m = re.search(r"const PROGRAMS\s*=\s*\[", h)
start = m.end()
depth = 1
i = start
while i < len(h) and depth > 0:
    if h[i] == "[": depth += 1
    elif h[i] == "]": depth -= 1
    i += 1
# i is now one past the closing ]
# Insert before the ]
insert_pos = i - 1  # position of ]

# Build new entries string
new_entries = []
for p in programs:
    e = (f'{{id:"{p["id"]}",s:"{p["s"]}",n:"{p["n"]}",en:"{p["en"]}",'
         f'deg:"{p["deg"]}",lvl:"{p["lvl"]}",stem:{p["stem"]},dur:"{p["dur"]}",'
         f'ddl:"{p["ddl"]}",lang:"{p["lang"]}",test:{{cls:"{p["test"]["cls"]}"}},'
         f'tui:"{p["tui"]}",url:"{p["url"]}"}}')
    new_entries.append(e)

# Check if the character before ] is a comma or not
before = h[insert_pos-1]
prefix = "," if before not in [",", "["] else ""
addition = prefix + ",".join(new_entries)
h = h[:insert_pos] + addition + h[insert_pos:]
print("Appended", len(new_entries), "PROGRAMS entries")

# ---------- Append to VERIFIED_DETAILS ----------
# Find VD Set end
m2 = re.search(r"const VERIFIED_DETAILS\s*=\s*new\s*Set\(\s*\[", h)
start2 = m2.end()
depth2 = 1
j = start2
while j < len(h) and depth2 > 0:
    if h[j] == "[": depth2 += 1
    elif h[j] == "]": depth2 -= 1
    j += 1
# j is now one past the closing ]
# Insert before ]
vd_insert = j - 1
new_vd = [p["url"] for p in programs]
before_vd = h[vd_insert-1]
prefix_vd = "," if before_vd not in [",", "["] else ""
vd_addition = prefix_vd + ",".join(f'"{u}"' for u in new_vd)
h = h[:vd_insert] + vd_addition + h[vd_insert:]
print("Appended", len(new_vd), "VD entries")

open(idx_path, "w", encoding="utf-8").write(h)
print("Done. File size:", len(h))
