# -*- coding: utf-8 -*-
"""Round 212: batch add 5 ME/AE PhDs
- umich-me-phd
- cornell-me-phd
- princeton-mae-phd
- caltech-me-phd
- stanford-aa-phd
FIX: re-locate VD Set on new_block after PROGRAMS append, not on original html.
"""
import os, re

BASE = os.path.dirname(os.path.abspath(__file__))
DET = os.path.join(BASE, "details")
os.makedirs(DET, exist_ok=True)

PROGRAMS = [
    {
        "id": "umich-me-phd",
        "s": "umich",
        "n": "机械工程博士",
        "en": "PhD in Mechanical Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years (BS direct) or 4 years (with MS)",
        "ddl": "Fall only: Dec 1 (priority fellowship); Feb 1 (final, requires confirmed advisor)",
        "lang": "TOEFL/IELTS required (Rackham Graduate School minimums)",
        "test": {"cls": "GRE not required"},
        "tui": "Full funding: tuition + stipend + health/dental benefits for 5 years (BS direct) or 4 years (with MS); via fellowship/GSRA/GSI/GSSA",
        "url": "details/umich-me-phd.html",
    },
    {
        "id": "cornell-me-phd",
        "s": "cornell",
        "n": "机械工程博士",
        "en": "PhD in Mechanical Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years",
        "ddl": "Fall only: Dec 1; no spring admission. Decisions by end of Feb, all by Apr 1; reply by Apr 15.",
        "lang": "TOEFL/IELTS required (Graduate School minimums)",
        "test": {"cls": "GRE not accepted for Fall 2027 cycle"},
        "tui": "Fully funded: first semester fellowship or TA to find advisor; thereafter GRA/TA/external fellowship (NSF/NDSEG/Sloan/Hertz/Cornell). Application fee $105.",
        "url": "details/cornell-me-phd.html",
    },
    {
        "id": "princeton-mae-phd",
        "s": "princeton",
        "n": "机械与航空航天工程博士",
        "en": "PhD in Mechanical and Aerospace Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5 years",
        "ddl": "Fall only: Dec 1, 11:59 PM ET. Matriculation only in September.",
        "lang": "TOEFL/IELTS required",
        "test": {"cls": "GRE not accepted"},
        "tui": "Full funding 5 years: tuition + stipend. Gordon Wu Fellowship: first-year full fellowship + $3,000 start grant + $5,000/year supplement years 1-5. Application fee $75.",
        "url": "details/princeton-mae-phd.html",
    },
    {
        "id": "caltech-me-phd",
        "s": "caltech",
        "n": "机械工程博士",
        "en": "PhD in Mechanical Engineering (Mechanical and Civil Engineering)",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "Fall only: Dec 15. Decisions by Apr 1. 250-300 applicants, 25-30 offers.",
        "lang": "TOEFL/IELTS required",
        "test": {"cls": "GRE not required; self-reported scores not considered"},
        "tui": "Full tuition + mandatory fees + living stipend for all PhD students; via fellowship/RA/TA. No terminal MS; PhD is the final degree objective. Application fee $100 (waiver available).",
        "url": "details/caltech-me-phd.html",
    },
    {
        "id": "stanford-aa-phd",
        "s": "stanford",
        "n": "航空航天博士",
        "en": "PhD in Aeronautics and Astronautics",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "5-6 years",
        "ddl": "Autumn only: Dec 2, 2026 (for Autumn 2027-28). One admission cycle per year; late applications not accepted.",
        "lang": "TOEFL/IELTS required for non-native English speakers",
        "test": {"cls": "GRE not required"},
        "tui": "Full funding at 20-hour RA level + tuition. Stanford Graduate Fellowships (3 years full support); Knight-Hennessy Scholars up to 3 years. External fellowships (NSF/Hertz/NDSEG) encouraged.",
        "url": "details/stanford-aa-phd.html",
    },
]

DETAIL_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{school} - {en}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',Roboto,sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.6}}
h1{{font-size:24px;border-bottom:2px solid #1a73e8;padding-bottom:8px}}
h2{{font-size:18px;color:#1a73e8;margin-top:24px}}
.card{{background:#f8f9fa;border-left:4px solid #1a73e8;padding:12px 16px;margin:12px 0;border-radius:4px}}
.meta{{display:grid;grid-template-columns:120px 1fr;gap:6px 12px;font-size:14px}}
.meta b{{color:#555}}
ul{{margin:6px 0;padding-left:20px}}
.note{{background:#fff3cd;border-left-color:#ffc107;padding:10px 14px;margin-top:16px;font-size:13px}}
a{{color:#1a73e8}}
</style>
</head>
<body>
<h1>{school} - {en}</h1>
<div class="card">
<div class="meta">
<b>Degree</b><span>{deg}</span>
<b>Level</b><span>Research Doctorate (PhD)</span>
<b>STEM</b><span>Yes</span>
<b>Duration</b><span>{dur}</span>
<b>Deadline</b><span>{ddl}</span>
<b>Language</b><span>{lang}</span>
<b>Standardized</b><span>{test_cls}</span>
<b>Funding</b><span>{tui}</span>
</div>
</div>

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

<h2>Admissions Requirements</h2>
<div class="card">
{requirements}
</div>

<h2>Research Areas</h2>
<div class="card">
{research}
</div>

<h2>Official Source</h2>
<div class="card">
{source}
</div>

<div class="note">
<strong>Note:</strong> This is a research-oriented PhD program. All admitted PhD students receive full financial support. Admission statistics shown are distribution ranges, not minimum thresholds. Course/credit details pending department bulletin verification.
</div>
</body>
</html>
"""

PAGES = {
    "umich-me-phd": {
        "school": "University of Michigan, Ann Arbor",
        "en": "PhD in Mechanical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years for BS direct admit; 4 years for students entering with a relevant MS",
        "ddl": "Fall only: December 1 (priority fellowship consideration, no confirmed advisor required); February 1 (final deadline, requires confirmed faculty advisor with funding).",
        "lang": "TOEFL/IELTS required per Rackham Graduate School minimums.",
        "test_cls": "GRE not required.",
        "tui": "Full funding package: tuition + registration fees + monthly stipend + health and dental benefits. 5 years for BS direct, 4 years for MS holders. Support via fellowship, GSRA (research), GSI (teaching), or GSSA.",
        "overview": "The Department of Mechanical Engineering at the University of Michigan offers a research PhD. Students admitted by December 1 are considered for fellowships without needing a pre-confirmed faculty advisor; students applying after December 1 must have a confirmed research advisor. The program emphasizes hands-on research with 100,000+ Michigan Engineers industry network.",
        "requirements": "<ul><li>BS in mechanical engineering or related engineering/science field</li><li>Application opens early September</li><li>Statement of Purpose, Personal Statement, CV, transcripts</li><li>3 letters of recommendation</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Advanced manufacturing and materials</li><li>Bioengineering and biomechanics</li><li>Thermosciences and energy systems</li><li>Mechanical systems and design</li><li>Fluid mechanics and aerodynamics</li><li>Robotics and control</li></ul>",
        "source": '<a href="https://me.engin.umich.edu/admissions/graduate/" target="_blank">ME Graduate Admissions</a> | <a href="https://me.engin.umich.edu/admissions/graduate/financial/" target="_blank">Financial Information</a>',
    },
    "cornell-me-phd": {
        "school": "Cornell University",
        "en": "PhD in Mechanical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years",
        "ddl": "Fall only: December 1. No spring admission. Initial decisions by end of February; all decisions complete by April 1; student reply by April 15.",
        "lang": "TOEFL/IELTS required per Cornell Graduate School minimums.",
        "test_cls": "GRE not accepted for Fall 2027 cycle.",
        "tui": "Fully funded: first semester fellowship or teaching assistantship to allow advisor search; thereafter GRA/TA/external fellowship (NSF/NDSEG/Sloan/Hertz/Cornell). Funding continues for the full time the student is in good standing. Application fee $105 (waiver available).",
        "overview": "The Sibley School of Mechanical and Aerospace Engineering offers a PhD in Mechanical Engineering. Applicants may apply directly from a bachelor's degree. The field admits only applicants with funding. A typical admitted student has GPA >3.5 (historical distribution, not minimum threshold).",
        "requirements": "<ul><li>BS in engineering or physical sciences</li><li>3 letters of recommendation</li><li>Personal statement</li><li>Academic statement of purpose</li><li>Resume or CV</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Energy and sustainability</li><li>Fluid mechanics and propulsion</li><li>Mechanics of materials and structures</li><li>Bioengineering and biomechanics</li><li>Design, manufacturing, and robotics</li><li>Theoretical and applied mechanics</li></ul>",
        "source": '<a href="https://www.duffield.cornell.edu/mae/phd/phd-admissions/" target="_blank">MAE PhD Admissions</a> | <a href="https://gradschool.cornell.edu/academics/fields-of-study/subject/mechanical-engineering/mechanical-engineering-phd-ithaca/" target="_blank">Graduate School ME PhD</a>',
    },
    "princeton-mae-phd": {
        "school": "Princeton University",
        "en": "PhD in Mechanical and Aerospace Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5 years",
        "ddl": "Fall only: December 1, 11:59 PM ET. Matriculation only in September; no other entry dates.",
        "lang": "TOEFL/IELTS required",
        "test_cls": "GRE not accepted.",
        "tui": "Full funding for 5 years: tuition + fees + stipend. Gordon Wu Fellowship (top engineering incoming PhD): first-year full fellowship + $3,000 start grant + $5,000/year supplement in years 1-5. Application fee $75 (waiver available).",
        "overview": "The Department of Mechanical and Aerospace Engineering offers a PhD that may be pursued directly after a bachelor's degree; no MSE is required. The department emphasizes close student-faculty collaboration. Applicants from math, materials, physics, chemical, civil, or electrical engineering backgrounds are encouraged to apply.",
        "requirements": "<ul><li>BS in engineering or science (MAE background not required; math/physics/chem/civil/EE all welcome)</li><li>Select research area of interest at application</li><li>Statement of Purpose, transcripts, CV</li><li>3 letters of recommendation</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Applied physics</li><li>Biomechanics and biomaterials</li><li>Control, robotics, and dynamical systems</li><li>Fluid mechanics</li><li>Materials science</li><li>Propulsion and energy sciences</li></ul>",
        "source": '<a href="https://mae.princeton.edu/graduate/admissions" target="_blank">MAE Graduate Admissions</a> | <a href="https://gradschool.princeton.edu/academics/degrees-requirements/fields-study/mechanical-and-aerospace-engineering" target="_blank">Graduate School MAE</a>',
    },
    "caltech-me-phd": {
        "school": "California Institute of Technology",
        "en": "PhD in Mechanical Engineering",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years",
        "ddl": "Fall only: December 15. Decisions posted by April 1. Typical 250-300 applications, 25-30 offers.",
        "lang": "TOEFL/IELTS required",
        "test_cls": "GRE not required; self-reported scores are not considered.",
        "tui": "Full tuition + mandatory fees + living stipend for all PhD students; via fellowship/RA/TA combination. No terminal MS: PhD is the final degree objective. Application fee $100 (waiver available).",
        "overview": "The Department of Mechanical and Civil Engineering (MCE) at Caltech offers a PhD emphasizing doctoral-level research. The program admits students directly to the PhD track; a terminal MS is awarded only in exceptional cases. Caltech's small size (25-30 offers per year) ensures close faculty mentorship.",
        "requirements": "<ul><li>BS in science or engineering related to an MCE option</li><li>Strong undergraduate math, physics, and engineering background</li><li>Personal statement, transcripts, letters of recommendation</li><li>TOEFL/IELTS (international applicants)</li><li>Work authorization required for most funding sources</li></ul>",
        "research": "<ul><li>Applied mechanics and materials</li><li>Fluid mechanics and aerodynamics</li><li>Control and dynamical systems</li><li>Bioengineering and medical engineering</li><li>Energy and sustainability</li><li>Geomechanics and civil engineering</li></ul>",
        "source": '<a href="https://mce.caltech.edu/academics/grad/admissions" target="_blank">MCE Graduate Admissions</a> | <a href="https://gradoffice.caltech.edu/financiaLsupport" target="_blank">Graduate Studies Financial Support</a>',
    },
    "stanford-aa-phd": {
        "school": "Stanford University",
        "en": "PhD in Aeronautics and Astronautics",
        "deg": "Doctor of Philosophy (PhD)",
        "dur": "5-6 years",
        "ddl": "Autumn only: December 2, 2026 (for Autumn 2027-28 matriculation). One admission cycle per year; late applications not accepted.",
        "lang": "TOEFL/IELTS required for non-native English speakers.",
        "test_cls": "GRE not required.",
        "tui": "Full funding at 20-hour RA level + tuition. Stanford Graduate Fellowships (3 years full support); Knight-Hennessy Scholars up to 3 years. External fellowships (NSF/Hertz/NDSEG) strongly encouraged.",
        "overview": "The Department of Aeronautics and Astronautics offers a PhD that may be pursued directly after a bachelor's degree; an MS is no longer required to apply. The program reviews applications holistically, including academic record, letters, SOP, personal qualities, and past accomplishments.",
        "requirements": "<ul><li>BS in engineering, physics, or comparable science program</li><li>Statement of Purpose</li><li>3 letters of recommendation</li><li>Transcripts</li><li>TOEFL/IELTS (international applicants)</li></ul>",
        "research": "<ul><li>Aerodynamics and fluid mechanics</li><li>Aircraft and spacecraft design</li><li>Control, guidance, and navigation</li><li>Propulsion and energy</li><li>Aerospace materials and structures</li><li>Astro- and space physics</li></ul>",
        "source": '<a href="https://aa.stanford.edu/academics-admissions/graduate-admissions/phd-admissions" target="_blank">AA PhD Admissions</a> | <a href="https://bulletin.stanford.edu/programs/AA-PHD" target="_blank">Bulletin AA-PHD</a>',
    },
}

# Write detail pages
for p in PROGRAMS:
    key = p["id"]
    d = PAGES[key]
    html = DETAIL_TEMPLATE.format(
        school=d["school"], en=d["en"], deg=d["deg"], dur=d["dur"],
        ddl=d["ddl"], lang=d["lang"], test_cls=d["test_cls"], tui=d["tui"],
        overview=d["overview"], requirements=d["requirements"],
        research=d["research"], source=d["source"],
    )
    path = os.path.join(DET, key + ".html")
    with open(path, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"Wrote: {key}.html")

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

def build_entry(p):
    return ('{{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"], ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"]["cls"].replace('"', "'"),
        tui=p["tui"].replace('"', "'"), url=p["url"],
    )

new_entries = ",\n".join(build_entry(p) for p in PROGRAMS)

# Step 1: append PROGRAMS (on original html)
m = re.search(r'const\s+PROGRAMS\s*=\s*\[', html)
start = m.end()
depth = 1
i = start
while i < len(html) and depth > 0:
    c = html[i]
    if c == '[': depth += 1
    elif c == ']': depth -= 1
    i += 1
insert_pos = i - 1
prefix = html[:insert_pos].rstrip()
suffix = html[insert_pos:]
if prefix.endswith('{'):
    new_block = prefix + "\n" + new_entries + "\n" + suffix
else:
    new_block = prefix + ",\n" + new_entries + "\n" + suffix

# Step 2: append VD entries on new_block (RE-LOCATE VD Set on new_block, not original html)
vd_entries = ",\n".join(f'"{p["url"]}"' for p in PROGRAMS)
m2 = re.search(r'VERIFIED_DETAILS\s*=\s*new\s+Set\s*\(\s*\[', new_block)
vstart = m2.end()
vdepth = 1
j = vstart
while j < len(new_block) and vdepth > 0:
    c = new_block[j]
    if c == '[': vdepth += 1
    elif c == ']': vdepth -= 1
    j += 1
vinsert_pos = j - 1
vprefix = new_block[:vinsert_pos].rstrip()
vsuffix = new_block[vinsert_pos:]
# Check if vprefix ends with a comma already
if vprefix.endswith(','):
    new_block = vprefix + "\n" + vd_entries + "\n" + vsuffix
elif vprefix.endswith('['):
    new_block = vprefix + "\n" + vd_entries + "\n" + vsuffix
else:
    new_block = vprefix + ",\n" + vd_entries + "\n" + vsuffix

# Ensure comma after last new VD entry if vsuffix starts with a string
# (vsuffix starts right after ], which is ");" so no comma needed between last VD and ])
# But vd_entries has no trailing comma; if vsuffix is ");" that's fine.

with open(idx_path, "w", encoding="utf-8") as f:
    f.write(new_block)

print(f"Appended {len(PROGRAMS)} PROGRAMS entries and {len(PROGRAMS)} VD entries")
print(f"Done. File size: {os.path.getsize(idx_path)}")
