# -*- coding: utf-8 -*-
"""Round 156: add 5 in-person half-verified detail pages."""
import re, os

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

PROGRAMS = [
    {
        "id": "uva-ms-global-commerce",
        "s": "uva",
        "n": "全球商学硕士（McIntire × ESMT Berlin）",
        "en": "Master of Science in Global Commerce (McIntire × ESMT Berlin)",
        "deg": "MS",
        "lvl": "m",
        "stem": 0,
        "dur": "9 months (September start; Fall Charlottesville + Spring Berlin + April Social Impact Project)",
        "ddl": "Rounds TBD pending site recovery",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GMAT/GRE requirement TBD pending site recovery; admissions profile, not minimum threshold"},
        "tui": "TBD pending site recovery",
        "url": "details/uva-ms-global-commerce.html",
        "school_zh": "弗吉尼亚大学",
        "college": "McIntire School of Commerce (partner: ESMT Berlin)",
        "website": "https://www.commerce.virginia.edu/ms-global",
        "summary": "9-month full-time in-person global degree. Fall semester in Charlottesville (McIntire core), Spring semester at ESMT Berlin (global business electives + seminars), then 5-week immersive Social Impact Project (SIP) at a global partner organization. 30 credits. Designed for recent undergraduate business majors/minors with a globally oriented major. Core courses include Global Challenges Sustainable Solutions, Global Strategy & Management I/II, Global Financial Markets, Global Marketing in the Digital Age, Business Analytics for Decision-Making, Global Operations & Supply Chain Management, Negotiation.",
        "tracks": ["Global Business Core (shared with ESMT)", "Social Impact Project capstone", "One ESMT elective"],
        "careers": ["Global management trainee", "International business development", "Global supply chain", "Global marketing", "Consulting cross-border practice"],
    },
    {
        "id": "umich-mse-aerospace",
        "s": "umich",
        "n": "航空航天工程硕士",
        "en": "Master of Science in Engineering (MSE) in Aerospace Engineering",
        "deg": "MSE",
        "lvl": "m",
        "stem": 1,
        "dur": "~16 months (30 credits, full-time in Ann Arbor)",
        "ddl": "Fall 1/15 (MSE); Winter 10/7",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GRE required for external MSE applicants; admissions profile, not minimum threshold"},
        "tui": "~$33,467/term nonresident (2026-27 Rackham)",
        "url": "details/umich-mse-aerospace-engineering.html",
        "school_zh": "密歇根大学安娜堡分校",
        "college": "Department of Aerospace Engineering, College of Engineering / Rackham",
        "website": "https://aero.engin.umich.edu/",
        "summary": "Rackham MSE in Aerospace Engineering. 30 credits: at least five 500-level AEROSP courses plus two approved mathematics courses, plus 15 approved elective credits. ~149 MS students (Fall 2025). Research is optional and selective; thesis track available. Areas include flight dynamics, propulsion, aerodynamics, controls, aerospace structures, space systems. Recent admitted profile combined GRE above 320 (V+Q), AWA 4.0+. SUGS combined-degree track available for UMich undergrads.",
        "tracks": ["Aerodynamics & Propulsion", "Flight Dynamics & Control", "Aerospace Structures", "Space Systems", "Autonomous Aerospace Systems"],
        "careers": ["Aerospace systems engineer", "Flight controls engineer", "Propulsion engineer", "Space systems engineer", "Defense/aviation R&D"],
    },
    {
        "id": "duke-meng-cyber",
        "s": "duke",
        "n": "网络安全工程硕士（Pratt 在校）",
        "en": "Master of Engineering in Cybersecurity (On-Campus)",
        "deg": "MEng",
        "lvl": "m",
        "stem": 1,
        "dur": "3-4 semesters on-campus (typically 1-1.5 years full-time)",
        "ddl": "Rounds TBD pending site recovery",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GRE/GMAT requirement TBD pending site recovery; admissions profile, not minimum threshold"},
        "tui": "~$34,310/semester (2025-26 campus Pratt MEng, ~$102,930 total over 3 semesters)",
        "url": "details/duke-meng-cybersecurity.html",
        "school_zh": "杜克大学",
        "college": "Pratt School of Engineering, Institute for Enterprise Engineering",
        "website": "https://masters.pratt.duke.edu/cybersecurity/",
        "summary": "Pratt MEng in Cybersecurity on-campus track (online 4-5 semester version excluded). 30 credits: 2 industry prep core (Business Fundamentals for Engineers, Management of High-Tech Industries) + 4 technical core (Intro to Cybersecurity Perspectives, Cybersecurity Risk Management, Multidisciplinary Cybersecurity: Government Public Policy Law, plus CYBERSEC 501/590) + 5 cybersecurity electives + 1 required internship/capstone. Three elective tracks: AI & Security, Technology, Technology Management. Typical courses include Ethical Hacking, Industrial Technology and Cybersecurity Analysis, Applying Machine Learning to Cybersecurity, Cybersecurity and National Security Law.",
        "tracks": ["AI & Security", "Technology (technical depth)", "Technology Management (leadership/strategy)"],
        "careers": ["Cybersecurity engineer", "Security analyst", "Risk manager", "Product security engineer", "Government/defense cyber policy"],
    },
    {
        "id": "cmu-ms-music-tech",
        "s": "cmu",
        "n": "音乐与技术硕士",
        "en": "Master of Science in Music and Technology",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "21 months / 4 semesters (late August start, May graduation)",
        "ddl": "Rounds TBD pending site recovery",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GRE requirement TBD pending site recovery; admissions profile, not minimum threshold"},
        "tui": "TBD pending site recovery",
        "url": "details/cmu-ms-music-technology.html",
        "school_zh": "卡内基梅隆大学",
        "college": "School of Music (with School of Computer Science and Department of ECE)",
        "website": "https://music.cmu.edu/academics/graduate/music-and-technology/",
        "summary": "Interdisciplinary MS jointly administered by School of Music, School of Computer Science, and Department of Electrical and Computer Engineering. 144 units: 60 units core (at least 24 music + 24 CS/ECE) + 24 support courses + 18 thesis research + 4 Music and Technology Seminar + 26 electives. Each student works with a graduate advisory committee across three schools. Required public performance/recital and written thesis. Areas: technologically assisted composition, computer music systems, music signal processing, acoustics and sound recording, music information retrieval, music cognition, musical robotics, new musical instruments.",
        "tracks": ["Computer Music Systems", "Audio Engineering & Signal Processing", "Music Information Retrieval", "Acoustics & New Instruments", "Music Cognition"],
        "careers": ["Audio engineer", "Music tech R&D", "Sound designer", "Acoustics engineer", "PhD continuation in music technology"],
    },
    {
        "id": "geo-msba",
        "s": "geo",
        "n": "商业分析硕士（McDonough 全日制在校）",
        "en": "Master of Science in Business Analytics (Full-Time, McDonough)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "10 months (Fall start, in-person cohort in Washington DC)",
        "ddl": "Fall 2026 start; rounds TBD pending site recovery",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GMAT/GRE requirement TBD pending site recovery; admissions profile, not minimum threshold"},
        "tui": "TBD pending site recovery",
        "url": "details/geo-msba-fulltime.html",
        "school_zh": "乔治城大学",
        "college": "McDonough School of Business",
        "website": "https://msb.georgetown.edu/msba/",
        "summary": "Full-time in-person MSBA at Georgetown main campus (Washington DC). 10-month lockstep cohort. STEM-designated. 2026 Fall inaugural class of 56 students: average GPA 3.5, average age 24, ~1 year professional experience, 46% female, 39% international, 16 countries / 26 languages. Technical toolkit: Python, R, SQL, NoSQL, Tableau, Apache Spark, AWS, LLM/AI tools. Culminating consulting capstone with a real client. Note: 16-month online part-time version excluded; this entry covers the in-person full-time cohort only.",
        "tracks": ["Core analytics: Python/R/SQL/NoSQL", "Cloud & big data: AWS, Spark", "Visualization: Tableau, Power BI", "AI/LLM applications", "Client consulting capstone"],
        "careers": ["Business analyst", "Data scientist (business)", "Marketing analytics", "Consulting (data-driven)", "Product analytics"],
    },
]

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{school_zh} {n} - {en}</title>
<style>
body{{font-family:-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.7}}
h1{{font-size:22px;border-bottom:3px solid #1a4480;padding-bottom:8px}}
h2{{font-size:16px;color:#1a4480;margin-top:24px}}
.card{{background:#f7f9fc;border-left:4px solid #1a4480;padding:14px 18px;margin:12px 0;border-radius:4px}}
.meta{{display:grid;grid-template-columns:1fr 1fr;gap:8px 24px;font-size:14px}}
.meta b{{color:#555}}
.tag{{display:inline-block;background:#e8eef7;color:#1a4480;padding:2px 10px;border-radius:12px;font-size:12px;margin-right:6px;margin-bottom:4px}}
ul{{margin:6px 0;padding-left:22px}}
.warn{{background:#fff8e6;border-left-color:#d4a017}}
a{{color:#1a4480}}
</style>
</head>
<body>
<h1>{school_zh} · {n}</h1>
<p style="color:#666;font-style:italic">{en}</p>

<div class="card">
<div class="meta">
<div><b>College:</b> {college}</div>
<div><b>Degree:</b> {deg}</div>
<div><b>Duration:</b> {dur}</div>
<div><b>Deadline:</b> {ddl}</div>
<div><b>Language:</b> {lang}</div>
<div><b>Test:</b> {test_cls}</div>
<div><b>Tuition:</b> {tui}</div>
<div><b>STEM:</b> {stem_tag}</div>
</div>
</div>

<h2>Program Overview</h2>
<div class="card">{summary}</div>

<h2>Tracks</h2>
<div class="card">{tracks_html}</div>

<h2>Career Outcomes</h2>
<div class="card">{careers_html}</div>

<h2>Official Website</h2>
<div class="card">
<a href="{website}" target="_blank">{website}</a>
</div>

<div class="card warn">
<b>Verification status:</b> half-verified page. Degree, duration, tracks and official link confirmed from school website; precise tuition, full curriculum list, detailed materials checklist and language minimums pending site recovery. Test scores are admissions profiles, not minimum thresholds.
</div>

<p style="text-align:center;color:#999;font-size:12px;margin-top:30px">Project Library Heartbeat - Round 156 - 2026-11-25</p>
</body>
</html>
"""


def render_detail(p):
    tracks_html = "".join(f"<span class='tag'>{t}</span>" for t in p["tracks"])
    careers_html = "<ul>" + "".join(f"<li>{c}</li>" for c in p["careers"]) + "</ul>"
    stem_tag = "STEM-designated" if p["stem"] == 1 else "Not STEM"
    return DETAIL_TEMPLATE.format(
        school_zh=p["school_zh"],
        n=p["n"], en=p["en"],
        college=p["college"], deg=p["deg"], dur=p["dur"],
        ddl=p["ddl"], lang=p["lang"], test_cls=p["test"]["cls"],
        tui=p["tui"], stem_tag=stem_tag,
        summary=p["summary"], tracks_html=tracks_html, careers_html=careers_html,
        website=p["website"],
    )


def main():
    html = open(INDEX, encoding="utf-8").read()

    for p in PROGRAMS:
        path = os.path.join(ROOT, p["url"].replace("/", os.sep))
        content = render_detail(p)
        open(path, "w", encoding="utf-8").write(content)
        print(f"[OK] generated: {p['url']} ({len(content)} chars)")

    start = html.index("const PROGRAMS=") + len("const PROGRAMS=")
    depth = 0
    i = start
    while i < len(html):
        ch = html[i]
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
            if depth == 0:
                end = i
                break
        i += 1
    existing = html[start:end]

    new_items = []
    for p in PROGRAMS:
        item = (
            '{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},dur:"{dur}",'
            'ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test_cls}"}},tui:"{tui}",url:"{url}"}}'
        ).format(
            id=p["id"], s=p["s"], n=p["n"], en=p["en"], deg=p["deg"], lvl=p["lvl"],
            stem=p["stem"], dur=p["dur"].replace('"', "'"),
            ddl=p["ddl"].replace('"', "'"),
            lang=p["lang"].replace('"', "'"),
            test_cls=p["test"]["cls"].replace('"', "'"),
            tui=p["tui"].replace('"', "'"),
            url=p["url"],
        )
        new_items.append(item)

    if existing.rstrip().endswith(","):
        insertion = existing.rstrip() + "\n" + ",\n".join(new_items) + "\n"
    else:
        insertion = existing.rstrip() + ",\n" + ",\n".join(new_items) + "\n"
    html = html[:start] + insertion + html[end:]
    print(f"[OK] PROGRAMS appended {len(PROGRAMS)}")

    vd_start = html.index("const VERIFIED_DETAILS=new Set([") + len("const VERIFIED_DETAILS=new Set(")
    depth = 0
    i = vd_start
    while i < len(html):
        ch = html[i]
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
            if depth == 0:
                vd_end = i
                break
        i += 1
    vd_existing = html[vd_start:vd_end]
    new_urls = [p["url"] for p in PROGRAMS]
    if vd_existing.rstrip().endswith(","):
        vd_new = vd_existing.rstrip() + "\n" + ",".join(f'"{u}"' for u in new_urls) + "\n"
    else:
        vd_new = vd_existing.rstrip() + ",\n" + ",".join(f'"{u}"' for u in new_urls) + "\n"
    html = html[:vd_start] + vd_new + html[vd_end:]
    print(f"[OK] VERIFIED_DETAILS appended {len(new_urls)}")

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


if __name__ == "__main__":
    main()
