import os, re, json, time
os.chdir(r"D:\work buddy\2026-11-05-14-15-52")

# 5 new programs: (id, s, n, en, deg, lvl, stem, dur, ddl, lang, test_cls, tui, url, website, summary, reqs)
PROGS = [
    {
        "id":"up-math-am",
        "s":"up",
        "n":"数学文学硕士（AM）",
        "en":"Master of Arts in Mathematics",
        "deg":"AM",
        "lvl":"m",
        "stem":"1",
        "dur":"1.5-2 years (Fall only)",
        "ddl":"February 15, 2027 (AM/MPhil); PhD Dec 8, 2026",
        "lang":"TOEFL / IELTS required for non-native English speakers",
        "test_cls":"GRE General not required (optional); Math Subject Test not required",
        "tui":"Per-credit SAS tuition (see SAS Bursar for 2027-28 rate)",
        "url":"details/up-math-am.html",
        "website":"https://www.math.upenn.edu/graduate-program/how-apply",
        "summary":"Penn Department of Mathematics terminal AM (Master of Arts) track in the School of Arts and Sciences. The AM is the course-work master's within the math graduate group, distinct from the PhD and the MPhil. Designed for students who want advanced math training as a stepping stone to PhD study in math or quantitative fields, or as a terminal degree.",
        "reqs":[
            "Online application opens October 1 each year",
            "Unofficial transcripts uploaded; official transcript required upon admission",
            "Three (3) letters of recommendation, preferably from mathematics faculty",
            "Statement of purpose",
            "Curriculum vitae / resume",
            "TOEFL or IELTS scores for non-native English speakers (waiver possible for US/English-speaking degree holders)",
            "GRE General optional; Math Subject Test optional",
            "No application fee waiver details for AM track beyond SAS general need-based waivers"
        ]
    },
    {
        "id":"nyu-math-ms",
        "s":"nyu",
        "n":"数学硕士（Courant）",
        "en":"Master of Science in Mathematics (Courant GSAS)",
        "deg":"MS",
        "lvl":"m",
        "stem":"1",
        "dur":"1.5-2 years (Fall/Spring/Summer entry)",
        "ddl":"Fall April 1; Spring November 1; Summer April 15 (5PM ET)",
        "lang":"TOEFL / IELTS required for non-native English speakers",
        "test_cls":"GRE General optional; Math Subject Test optional (no disadvantage if absent)",
        "tui":"Per-point GSAS tuition (see NYU Bursar for 2027-28 rate)",
        "url":"details/nyu-math-ms.html",
        "website":"https://math.nyu.edu/dynamic/graduate/ms-gsas/admission/",
        "summary":"NYU Courant Institute of Mathematical Sciences MS in Mathematics through the Graduate School of Arts & Science. A flexible course-work master's covering pure math, applied math, numerical analysis, and probability. Distinct from MS in Mathematics in Finance (separate admission) and MS in Scientific Computing (joint Math-CS).",
        "reqs":[
            "Online application via NYU GSAS",
            "Official transcripts from all post-secondary institutions",
            "Three (3) letters of recommendation, at least two from math/science faculty",
            "Statement of purpose",
            "Curriculum vitae / resume",
            "TOEFL or IELTS (waiver for English-medium bachelor's/master's)",
            "GRE General optional; Math Subject Test optional; no penalty for not submitting",
            "Strong quantitative background: multivariable calculus, linear algebra, real analysis recommended"
        ]
    },
    {
        "id":"ut-astro-msc",
        "s":"ut",
        "n":"天文学与天体物理学硕士",
        "en":"Master of Science in Astronomy & Astrophysics",
        "deg":"MSc",
        "lvl":"m",
        "stem":"1",
        "dur":"3 sessions full-time (Fall/Winter/Spring); 3-year time limit",
        "ddl":"Early December for Fall entry (see SGS / Dunlap Institute for current cycle)",
        "lang":"TOEFL / IELTS / Duolingo required for non-native English speakers",
        "test_cls":"No GRE requirement (per SGS Department of Astronomy & Astrophysics)",
        "tui":"Per-session SGS tuition; see UofT Feen for 2027-28 rate",
        "url":"details/ut-astro-msc.html",
        "website":"https://www.sgs.utoronto.ca/programs/astronomy-and-astrophysics/",
        "summary":"University of Toronto Department of Astronomy & Astrophysics (Dunlap Institute) MSc. The MSc is offered as a research-track degree, often as a preliminary phase before PhD continuation. Students complete 2.0 required full-course equivalents (AST1501Y and AST1500Y) with different supervisors, original research throughout, and an oral committee exam. Physics/mathematics preparation is acceptable when astronomy undergraduate training is not extensive.",
        "reqs":[
            "Appropriate bachelor's degree with high academic standing (A-/A range)",
            "Physics/mathematics background acceptable in lieu of astronomy undergraduate major",
            "Three (3) letters of recommendation",
            "Statement of purpose / research proposal",
            "Curriculum vitae / resume",
            "TOEFL / IELTS / Duolingo scores (see SGS General Regulations 4.3)",
            "On-campus full-time residency required",
            "Minimum 1.5 FCE additional coursework beyond the two required research courses"
        ]
    },
    {
        "id":"nyu-a3sr-ms",
        "s":"nyu",
        "n":"应用统计学（社会科学研究）硕士",
        "en":"MS in Applied Statistics for Social Science Research",
        "deg":"MS",
        "lvl":"m",
        "stem":"1",
        "dur":"Flexible credit 34-44; full-time or part-time (up to 6 years)",
        "ddl":"February 1 (Fall only; no Spring/Summer entry)",
        "lang":"TOEFL 105 / IELTS 7.5 / Duolingo 125 (successful candidates generally at or above these)",
        "test_cls":"GRE General optional (holistic review; no disadvantage if absent)",
        "tui":"Per-credit Steinhardt tuition (see NYU Bursar for 2027-28 rate)",
        "url":"details/nyu-a3sr-ms.html",
        "website":"https://steinhardt.nyu.edu/degree/ms-applied-statistics-social-science-research",
        "summary":"NYU Steinhardt MS in Applied Statistics for Social Science Research (A3SR). A flexible-credit master's training advanced quantitative research techniques for social, behavioral, and health sciences. Three concentrations: Computational Methods (CPM), Data Science for Social Impact (DSI), General Applied Statistics (GAS). A placement exam on math/stat background is required after admission to determine first-semester course placement.",
        "reqs":[
            "Online application via NYU Steinhardt",
            "Résumé / CV",
            "Statement of purpose",
            "Letters of recommendation (typically 2-3)",
            "Transcripts",
            "TOEFL 105 / IELTS 7.5 / Duolingo 125 (non-native English)",
            "Quantitative background: math/stat/CS major or minor strongly preferred; other quantitative disciplines encouraged",
            "Online competency exam after acceptance (math/stat placement)"
        ]
    },
    {
        "id":"up-amcs-ms",
        "s":"up",
        "n":"应用数学与计算科学硕士",
        "en":"Master of Science in Applied Mathematics and Computational Science (AMCS)",
        "deg":"MS",
        "lvl":"m",
        "stem":"1",
        "dur":"Fall only; typical 1.5-2 years",
        "ddl":"February 5, 2027 (Master's); PhD December 8, 2026",
        "lang":"TOEFL / IELTS required; waived for 4-year English-medium degree",
        "test_cls":"GRE General not required but suggested; Math Subject Test suggested",
        "tui":"Per-credit SEAS/SAS tuition (see Penn Bursar for 2027-28 rate)",
        "url":"details/up-amcs-ms.html",
        "website":"https://amcs.upenn.edu/admission/",
        "summary":"Penn AMCS (Applied Mathematics and Computational Science) interdisciplinary graduate program offering both MS and PhD. Trains students in advanced mathematics applied to empirical science, medicine, and engineering. MS track is course-work focused and distinct from the PhD track. Located in the Department of Mathematics, open to Penn SEAS and SAS students.",
        "reqs":[
            "Online application opens October 1, 2026",
            "Unofficial transcripts; official upon admission",
            "Three (3) letters of recommendation, preferably from math/science faculty",
            "Statement of purpose",
            "Curriculum vitae / resume",
            "TOEFL / IELTS (waiver for 4-year English-medium degree)",
            "GRE General not required but suggested; Math Subject Test suggested",
            "Strong math background: real analysis, advanced linear algebra, probability recommended"
        ]
    }
]

TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{n} | {s_upper}</title>
<style>
body{{font-family:-apple-system,"Segoe UI",Roboto,"PingFang SC","Microsoft YaHei",sans-serif;max-width:980px;margin:24px auto;padding:0 20px;color:#222;line-height:1.65;background:#fafafa}}
h1{{font-size:24px;border-bottom:3px solid #8b1a1a;padding-bottom:8px;margin-bottom:4px}}
.sub{{color:#666;margin-bottom:20px;font-size:14px}}
.grid{{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin:18px 0}}
.card{{background:#fff;border:1px solid #e3e3e3;border-radius:8px;padding:14px 16px;box-shadow:0 1px 2px rgba(0,0,0,0.03)}}
.card h3{{margin:0 0 8px;font-size:15px;color:#8b1a1a;border-bottom:1px solid #f0d6d6;padding-bottom:6px}}
.card p,.card li{{font-size:14px;margin:4px 0}}
.kv{{display:flex;justify-content:space-between;padding:3px 0;font-size:14px}}
.kv b{{color:#444}}
a{{color:#8b1a1a}}
.flag{{display:inline-block;background:#fff4e5;color:#b45309;padding:2px 8px;border-radius:10px;font-size:12px;margin-left:6px}}
ul{{padding-left:20px;margin:6px 0}}
</style>
</head>
<body>
<h1>{n}</h1>
<div class="sub">{en} · {s_upper} · {deg}<span class="flag">半核验页 · 课程/学分/材料清单待补</span></div>
<div class="grid">
  <div class="card"><h3>项目概览</h3><p>{summary}</p></div>
  <div class="card"><h3>关键参数</h3>
    <div class="kv"><b>学位</b><span>{deg}</span></div>
    <div class="kv"><b>层级</b><span>{lvl_cn}</span></div>
    <div class="kv"><b>STEM</b><span>{stem_cn}</span></div>
    <div class="kv"><b>学制</b><span>{dur}</span></div>
    <div class="kv"><b>申请截止</b><span>{ddl}</span></div>
    <div class="kv"><b>语言要求</b><span>{lang}</span></div>
    <div class="kv"><b>标化</b><span>{test_cls}</span></div>
    <div class="kv"><b>学费</b><span>{tui}</span></div>
  </div>
  <div class="card"><h3>申请材料 / 要求</h3><ul>{req_html}</ul></div>
  <div class="card"><h3>官方来源</h3>
    <p>学校官网：<a href="{website}" target="_blank">{website}</a></p>
    <p>本页为半核验页，课程设置、精确学分、完整材料清单字段待后续补核。</p>
    <p>录取分数若官方公布，仅作"录取分布，非最低门槛"参考。</p>
  </div>
</div>
</body>
</html>
"""

def lvl_cn(v): return "硕士" if v=="m" else "博士"
def stem_cn(v): return "STEM 认证" if v=="1" else "非 STEM"

# Write detail pages
for p in PROGS:
    req_html = "".join(f"<li>{r}</li>" for r in p["reqs"])
    html = TEMPLATE.format(
        n=p["n"], s_upper=p["s"].upper(), en=p["en"], deg=p["deg"],
        summary=p["summary"], dur=p["dur"], ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test_cls"], tui=p["tui"],
        lvl_cn=lvl_cn(p["lvl"]), stem_cn=stem_cn(p["stem"]),
        req_html=req_html, website=p["website"]
    )
    open(p["url"],"w",encoding="utf-8").write(html)
    print("Wrote:", p["url"])

# Append PROGRAMS entries (id,s,n,en,deg,lvl,stem,dur,ddl,lang,test,tui,url)
PROGRAMS_BLOCK = []
for p in PROGS:
    PROGRAMS_BLOCK.append(
        '{{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(**p)
    )

with open("index_main.html","r",encoding="utf-8") as f:
    html = f.read()

# Locate PROGRAMS array end via bracket-depth matching starting at "const PROGRAMS="
m = re.search(r"const PROGRAMS\s*=\s*\[", html)
assert m, "PROGRAMS array not found"
start = m.end()  # position after [
depth = 1
i = start
while i < len(html) and depth > 0:
    c = html[i]
    if c == "[": depth += 1
    elif c == "]": depth -= 1
    i += 1
prog_end = i - 1  # position of closing ]
# Insert before ], add comma if prior char not [
before = html[:prog_end].rstrip()
if not before.endswith("[") and not before.endswith(","):
    before += ","
insert_text = "\n" + ",".join(PROGRAMS_BLOCK) + "\n"
html = before + insert_text + html[prog_end:]

# Locate VERIFIED_DETAILS Set(...) end via paren-depth matching
m2 = re.search(r"const VERIFIED_DETAILS\s*=\s*new Set\(", html)
assert m2, "VERIFIED_DETAILS not found"
start2 = m2.end()  # position after (
depth = 1
i = start2
while i < len(html) and depth > 0:
    c = html[i]
    if c == "(": depth += 1
    elif c == ")": depth -= 1
    i += 1
vd_end = i - 1  # position of closing )
# Inside the set, the last element is a "..." before ]. We insert before ].
# Find ] between start2 and vd_end
bracket_pos = html.rfind("]", start2, vd_end)
assert bracket_pos > 0, "VD array close not found"
# Insert before ]
before_vd = html[:bracket_pos].rstrip()
if not before_vd.endswith("[") and not before_vd.endswith(","):
    before_vd += ","
vd_entries = ",".join(f'"{p["url"]}"' for p in PROGS)
html = before_vd + "\n" + vd_entries + "\n" + html[bracket_pos:]

with open("index_main.html","w",encoding="utf-8") as f:
    f.write(html)
print(f"Appended {len(PROGS)} PROGRAMS entries and {len(PROGS)} VD entries")
print("Done. File size:", len(html))
