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

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

PROGRAMS = [
    {
        "id": "cmu-msppm-dc",
        "s": "cmu",
        "n": "公共政策与管理硕士（华盛顿特区方向）",
        "en": "Master of Science in Public Policy and Management - Washington DC (MSPPM-DC)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "2 years (Year 1 Pittsburgh + Year 2 DC, 4 semesters with required summer internship)",
        "ddl": "Fall 1/15 priority (check official site for rounds)",
        "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-msppm-washington-dc.html",
        "school": "Carnegie Mellon University",
        "school_zh": "卡内基梅隆大学",
        "college": "Heinz College of Information Systems and Public Policy",
        "website": "https://www.heinz.cmu.edu/programs/public-policy-management-master/washington-dc/",
        "summary": "Heinz College MSPPM one of four pathways: Year 1 in Pittsburgh completes core coursework and required summer internship; Year 2 relocates to Washington DC, with ~30 hrs/week (4 days) Heinz Policy Fellowship at Congress, think tanks, federal agencies or international organizations. Core courses include How Ideas Become Policy, Leadership/Management Workshop: How Washington Works, Federal Budget Policy, Program Evaluation, Cost-Benefit Analysis, and Policy Analysis Capstone.",
        "tracks": ["Policy Analysis (default DC concentration)", "Other concentrations require early advisor planning"],
        "careers": ["Federal government / Congress", "Think tanks / international organizations", "National security / foreign policy", "Consulting public sector practice"],
    },
    {
        "id": "cmu-ms-etim",
        "s": "cmu",
        "n": "工程与技术创新管理硕士",
        "en": "Master of Science in Engineering and Technology Innovation Management (ETIM)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1 year full-time (2 semesters Jan-Dec, with required summer internship)",
        "ddl": "1/31 extended deadline (March notification) / 8/31 (check official site)",
        "lang": "TOEFL/IELTS minimum TBD pending site recovery",
        "test": {"cls": "GRE required; admissions profile, not minimum threshold"},
        "tui": "TBD pending site recovery (application fee $75)",
        "url": "details/cmu-ms-etim.html",
        "school": "Carnegie Mellon University",
        "school_zh": "卡内基梅隆大学",
        "college": "College of Engineering, Department of Engineering and Public Policy (EPP)",
        "website": "https://www.cmu.edu/engineering-etim/",
        "summary": "Designed for students with engineering/science/CS backgrounds, training technology business leaders. Six core courses (54 units): Strategy and Management of Technological Innovation, ETIM Seminar on Innovation Management in Practice, Engineering & Technology Innovation Management in Practice, Product or Process Project Course, Data Science for Technology Innovation and Policy, Finance for Innovation Management; plus 18 units engineering/technology electives. Five career tracks: Analytics, Product Management, Consulting, Engineering R&D, Entrepreneurship. Eligible for STEM OPT extension.",
        "tracks": ["Analytics", "Product Management", "Consulting", "Engineering R&D", "Entrepreneurship"],
        "careers": ["Technical product manager", "Technology consulting", "R&D management", "Startup technical founder", "Innovation strategy"],
    },
    {
        "id": "uva-ms-commerce",
        "s": "uva",
        "n": "商学硕士（McIntire）",
        "en": "Master of Science in Commerce (McIntire School of Commerce)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "10 months (August start, Fall + Spring + Global Immersion)",
        "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-commerce.html",
        "school": "University of Virginia",
        "school_zh": "弗吉尼亚大学",
        "college": "McIntire School of Commerce",
        "website": "https://www.commerce.virginia.edu/ms-commerce",
        "summary": "Designed for recent non-business majors (liberal arts / STEM). 10-month full-time in-person in Charlottesville. 40-credit Integrated Core Experience covering Finance, Strategy, Analytics, Leadership, then one specialization track. Includes faculty-led Global Immersion Experience overseas. STEM-designated. Class of 2025 salary and employment data TBD pending site recovery.",
        "tracks": ["Business Analytics", "Finance", "Marketing & Management", "Biotechnology"],
        "careers": ["Business analyst", "Financial analyst", "Marketing", "Strategy consulting", "Biotech industry business roles"],
    },
    {
        "id": "umich-ms-robotics",
        "s": "umich",
        "n": "机器人学硕士",
        "en": "Master of Science in Robotics",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "3-4 semesters (Fall only, full-time)",
        "ddl": "Fall 1/15",
        "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 (Rackham tuition standard)",
        "url": "details/umich-ms-robotics.html",
        "school": "University of Michigan, Ann Arbor",
        "school_zh": "密歇根大学安娜堡分校",
        "college": "Michigan Robotics, Rackham Graduate School",
        "website": "https://robotics.umich.edu/academics/graduate/",
        "summary": "Interdisciplinary robotics MS established 2014, housed in $75M Ford Robotics Building (opened 2021). Core coursework spans Sensing, Reasoning, Acting, cross-listed across ME, ECE, CS. ~100+ MS students. MS students typically self-fund (PhD students receive full funding). MS and PhD share core coursework; MS is a terminal degree.",
        "tracks": ["Perception / Sensing", "Reasoning / Decision Making", "Control / Acting", "Human-Robot Interaction", "Autonomous Systems"],
        "careers": ["Robotics engineer", "Autonomous driving R&D", "Automation systems engineer", "Perception/control algorithm engineer", "PhD continuation"],
    },
    {
        "id": "duke-mem-campus",
        "s": "duke",
        "n": "工程管理硕士（Pratt 在校一年制）",
        "en": "Master of Engineering Management (MEM, On-Campus)",
        "deg": "MEM",
        "lvl": "m",
        "stem": 1,
        "dur": "1 year (2 semesters full-time on campus, Fall start)",
        "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": "$36,225/semester (2026-27), ~$72,450 total for two semesters",
        "url": "details/duke-mem-campus.html",
        "school": "Duke University",
        "school_zh": "杜克大学",
        "college": "Pratt School of Engineering",
        "website": "https://masters.pratt.duke.edu/management/overview/",
        "summary": "Pratt School of Engineering on-campus 1-year MEM (this entry covers the in-person version only; the 2-year online version is excluded). 30 credits: 4 technical engineering electives from hundreds of Duke technical courses (6 study tracks) + 4 business/management core courses + 1 internship. Class of 2025 average US base salary $105,200; 92% employment within 6 months. Positioned as a tech-savvy alternative to MBA.",
        "tracks": ["6 study tracks (see official site)", "Technical engineering electives x4", "Business and management core x4"],
        "careers": ["Engineering project manager", "Technical product manager", "Technology consulting", "Operations management", "Fintech/tech company business roles"],
    },
]

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 155 - 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()

    # 1. Generate detail pages
    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)")

    # 2. Append PROGRAMS - bracket-depth match
    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)}")

    # 3. Append VERIFIED_DETAILS
    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()
