import re, os

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

programs = [
    {
        "id": "umich-aero-mse",
        "s": "umich",
        "n": "Aerospace Engineering MSE",
        "en": "Master of Science in Engineering - Aerospace Engineering",
        "deg": "MSE",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (Rackham graduate)",
        "ddl": "Jan 15, 2027 (Fall); Oct 7 (Winter)",
        "lang": "TOEFL / IELTS (Rackham minimum)",
        "test": "GRE required for MSE applicants (PhD/SUGS not required)",
        "tui": "待补",
        "url": "details/umich-aero-mse.html"
    },
    {
        "id": "notre-msae",
        "s": "notre",
        "n": "Aerospace Engineering MSAE",
        "en": "Master of Science in Aerospace Engineering",
        "deg": "MSAE",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (research-based)",
        "ddl": "Dec 31, 2026 (Fall); Oct 15 (Spring)",
        "lang": "TOEFL / IELTS / Duolingo",
        "test": "GRE optional",
        "tui": "待补",
        "url": "details/notre-msae.html"
    },
    {
        "id": "usc-aero-ms",
        "s": "usc",
        "n": "Aerospace Engineering MS",
        "en": "Master of Science in Aerospace Engineering",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (Viterbi graduate)",
        "ddl": "Dec 15, 2026 (Fall scholarship); Jan 15 (Fall final); Oct 15 (Spring)",
        "lang": "TOEFL / IELTS (USC graduate standard)",
        "test": "GRE not required for 2027 applications",
        "tui": "待补",
        "url": "details/usc-aero-ms.html"
    },
    {
        "id": "ucsd-se-ms",
        "s": "ucsd",
        "n": "Structural Engineering MS",
        "en": "Master of Science in Structural Engineering",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (48 units)",
        "ddl": "Dec 15, 2026 (Fall priority)",
        "lang": "TOEFL 85 / IELTS 7.0 / Duolingo 120",
        "test": "GRE permanently waived",
        "tui": "待补",
        "url": "details/ucsd-se-ms.html"
    },
    {
        "id": "uva-se-ms",
        "s": "uva",
        "n": "Systems Engineering MS",
        "en": "Master of Science in Systems Engineering",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (30 credits)",
        "ddl": "Jan 6, 2027 (Fall, with financial aid); Sept 30 (Spring)",
        "lang": "TOEFL / IELTS (UVA Engineering standard)",
        "test": "GRE optional (waived for 2026)",
        "tui": "待补",
        "url": "details/uva-se-ms.html"
    },
]

def detail_page(p):
    stem_label = "STEM" if p["stem"] else "Non-STEM"
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{p['en']} - {p['s'].upper()}</title>
<style>
body {{ font-family: -apple-system, "Segoe UI", Roboto, sans-serif; max-width: 960px; margin: 0 auto; padding: 24px; color: #222; line-height: 1.6; }}
h1 {{ font-size: 22px; border-bottom: 2px solid #2c5aa0; padding-bottom: 8px; }}
h2 {{ font-size: 16px; color: #2c5aa0; margin-top: 24px; }}
.card {{ background: #f7f9fc; border: 1px solid #dce4f0; border-radius: 8px; padding: 16px; margin: 12px 0; }}
.meta {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 16px 0; }}
.meta div {{ background: #eef3fb; padding: 8px 12px; border-radius: 6px; font-size: 13px; }}
.tag {{ display: inline-block; background: #2c5aa0; color: #fff; padding: 2px 10px; border-radius: 12px; font-size: 12px; margin-right: 6px; }}
.pending {{ color: #c0392b; font-style: italic; }}
ul {{ padding-left: 20px; }}
</style>
</head>
<body>
<h1>{p['en']}</h1>
<p><span class="tag">{p['deg']}</span><span class="tag">{stem_label}</span></p>

<div class="meta">
  <div><b>Duration:</b><br>{p['dur']}</div>
  <div><b>Deadline:</b><br>{p['ddl']}</div>
  <div><b>Language:</b><br>{p['lang']}</div>
  <div><b>Test:</b><br>{p['test']}</div>
  <div><b>Tuition:</b><br>{p['tui']}</div>
</div>

<div class="card">
<h2>Program Overview</h2>
<p>{overview_text(p['id'])}</p>
</div>

<div class="card">
<h2>Degree Requirements</h2>
{requirements_text(p['id'])}
</div>

<div class="card">
<h2>Core Curriculum</h2>
{curriculum_text(p['id'])}
</div>

<div class="card">
<h2>Admissions</h2>
{admissions_text(p['id'])}
</div>

<div class="card">
<h2>Notes</h2>
<p class="pending">Course details and exact tuition figures pending further verification. This is a semi-verified page based on official program pages and graduate catalog.</p>
</div>

</body>
</html>
"""

def overview_text(pid):
    if pid == "umich-aero-mse":
        return "The Master of Science in Engineering (MSE) in Aerospace Engineering at University of Michigan Rackham Graduate School / Department of Aerospace Engineering is a research-oriented terminal master's program. Research areas include aerodynamics, aerospace propulsion, autonomous vehicles, computational fluid dynamics, controls, ergonomics, gas dynamics, guidance/navigation/control, materials and structures, orbital mechanics, and space systems. The department admits Fall and Winter (Winter for advanced standing / internal students)."
    if pid == "notre-msae":
        return "The Master of Science in Aerospace Engineering (MSAE) at University of Notre Dame College of Engineering / Department of Aerospace and Mechanical Engineering (AME) is a research-based thesis program. Research pillars span bioengineering, computation, fluid mechanics, materials/energy/manufacturing, and robotics and controls. The department's primary degree is the PhD; MSAE students are admitted to the same research groups."
    if pid == "usc-aero-ms":
        return "The Master of Science in Aerospace Engineering at USC Viterbi School of Engineering / Department of Aerospace and Mechanical Engineering (AME) is a professional terminal master's program. Students may choose among several specializations including Aerospace Engineering general, Dynamics and Control, Computational Fluid and Solid Mechanics, Astronautical Engineering, and a dual-degree option with Engineering Management. The program is designed for industry roles in aerospace, defense, and related industries."
    if pid == "ucsd-se-ms":
        return "The Master of Science in Structural Engineering at UC San Diego Jacobs School of Engineering / Department of Structural Engineering is a research-oriented terminal master's program. The department's five primary research areas are Advanced Composites and Aerospace Structural Systems, Computational Mechanics, Earthquake Engineering, Geotechnical Engineering, and Structural Health Monitoring / Prognosis / Validated Simulations. Two MS plans are available: Comprehensive Examination Plan and Thesis Plan."
    if pid == "uva-se-ms":
        return "The Master of Science in Systems Engineering at University of Virginia School of Engineering and Applied Science / Department of Systems and Information Engineering (SIE) is a research-oriented MS. Students are admitted into SIE research subgroups and most funded offers include GRA/GTA positions with a default stipend. The MS is distinct from the M.E. on-Grounds professional degree and the VEO online M.E. (which is excluded as part-time/distance)."
    return ""

def requirements_text(pid):
    if pid == "umich-aero-mse":
        return """<ul>
<li>Total: Rackham MSE credit hours (typically 30 credits)</li>
<li>Fall admission deadline: January 15 (MSE); Winter admission deadline: October 7</li>
<li>PhD deadline: December 15 (direct PhD without master's is encouraged)</li>
<li>SUGS track: UMich BSE Aerospace students may double-count up to 9 credits toward both BSE and MSE</li>
<li>Minimum undergraduate preparation: solid math and engineering (physics, applied physics, math, or any engineering discipline eligible)</li>
<li>For applicants without engineering background: FE exam mechanical engineering discipline score recommended</li>
</ul>"""
    if pid == "notre-msae":
        return """<ul>
<li>Research-based thesis MS (1 semester residency minimum per Graduate School)</li>
<li>Fall admission deadline: December 31; Spring admission deadline: October 15</li>
<li>GRE General Test optional</li>
<li>English proficiency: TOEFL / IELTS / Duolingo</li>
<li>Application materials: online application, Statement of Intent, CV, 3 letters of recommendation, unofficial transcripts</li>
<li>Note: the department's primary graduate degree is the PhD; MSAE has limited funding</li>
<li>Contact: Ryan McClarren, Director of Graduate Studies, rmcclarr@nd.edu</li>
</ul>"""
    if pid == "usc-aero-ms":
        return """<ul>
<li>Total: Viterbi MS credit hours (typically 27-30 units)</li>
<li>Fall scholarship consideration deadline: December 15; Fall final deadline: January 15</li>
<li>Spring general deadline: October 15</li>
<li>Specializations: Aerospace Engineering general, Dynamics and Control, Computational Fluid and Solid Mechanics, Astronautical Engineering</li>
<li>GRE not required for 2027 applications</li>
<li>Letter of Recommendation: optional for Aerospace MS (2 required for Astronautical MS)</li>
<li>Application materials: transcripts, resume/CV, Personal Statement</li>
</ul>"""
    if pid == "ucsd-se-ms":
        return """<ul>
<li>Total: 48 units of credit</li>
<li>Comprehensive Examination Plan: 48 units of regular graduate courses (12 four-unit courses), all letter-graded</li>
<li>Thesis Plan: 36 units (9 courses) regular graduate courses + 12 units SE 299 master's thesis research (S/U allowed)</li>
<li>Three quarters of SE 290 required (not counted toward coursework units)</li>
<li>Up to 8 units of approved upper-division undergraduate courses may count toward MS degree</li>
<li>Minimum GPA 3.0 on 4.0 scale</li>
<li>Five research focus areas: Advanced Composites & Aerospace Structural Systems, Computational Mechanics, Earthquake Engineering, Geotechnical Engineering, Structural Health Monitoring / Prognosis / Validated Simulations</li>
</ul>"""
    if pid == "uva-se-ms":
        return """<ul>
<li>Total: 30 graduate-level credits, at least 18 credits in major study</li>
<li>4000-level or below courses do not count toward Master's degree</li>
<li>Up to 12 transfer credits allowed (B or better from recognized institution)</li>
<li>Fall financial-aid deadline: January 6; Spring deadline: September 30</li>
<li>Most accepted MS students receive funding via GRA / GTA / fellowships; default stipend $27,037.50/year plus tuition and health insurance</li>
<li>Admission is by SIE research subgroup; students are matched with faculty advisor during first year</li>
<li>Distinct from M.E. on-Grounds and VEO online M.E. (excluded as part-time/distance)</li>
</ul>"""
    return ""

def curriculum_text(pid):
    if pid == "umich-aero-mse":
        return """<ul>
<li>Core aerospace graduate coursework</li>
<li>Research areas: aerodynamics, aerospace propulsion, autonomous vehicles, computational fluid dynamics, controls, gas dynamics, guidance/navigation/control, materials and structures, orbital mechanics, space systems</li>
<li>Technical electives across Rackham graduate departments</li>
<li>Faculty-mentored research / thesis optional</li>
<li>SUGS track: up to 9 double-counted graduate credits</li>
</ul>"""
    if pid == "notre-msae":
        return """<ul>
<li>Graduate coursework in chosen research pillar (bioengineering, computation, fluid mechanics, materials/energy/manufacturing, robotics and controls)</li>
<li>Graduate seminar series</li>
<li>Thesis research credits under AME faculty advisor</li>
<li>Interdisciplinary electives across College of Engineering and Science</li>
<li>Access to state-of-the-art facilities and $20M+ external research grants per year</li>
<li>Final oral defense of written thesis</li>
</ul>"""
    if pid == "usc-aero-ms":
        return """<ul>
<li>Core aerospace engineering graduate coursework</li>
<li>Specialization options: Dynamics and Control, Computational Fluid and Solid Mechanics, general Aerospace Engineering, Astronautical Engineering</li>
<li>Electives across Viterbi departments (EE, CS, Mechanical Engineering, Astronautics)</li>
<li>Optional dual-degree with MS Engineering Management</li>
<li>Industry-relevant project courses</li>
<li>Merit-based partial scholarships available by Dec 15 / Aug 31 scholarship deadlines</li>
</ul>"""
    if pid == "ucsd-se-ms":
        return """<ul>
<li>Required: 3 quarters of SE 290 graduate seminar</li>
<li>Focus sequences in Solid Mechanics (SE 271, SE 272 + SE 273 / SE 252 / SE 235), Earthquake Engineering, Geotechnical Engineering, Composites, Structural Health Monitoring</li>
<li>Thesis Plan: SE 299 (12 units) master's thesis + oral defense with 3-faculty committee</li>
<li>Technical electives across Jacobs School of Engineering</li>
<li>Comprehensive Examination Plan: passing exam across chosen focus area</li>
<li>Up to 8 units of upper-division undergraduate coursework allowed</li>
</ul>"""
    if pid == "uva-se-ms":
        return """<ul>
<li>30 graduate-level credits, minimum 18 in Systems Engineering major</li>
<li>Core coursework in systems modeling, optimization, stochastic processes, human factors, data analytics</li>
<li>Research subgroups: e.g., adaptive decision systems, healthcare systems, resilience, transportation systems, cyber-physical systems</li>
<li>Faculty-mentored research (GRA) expected for funded students</li>
<li>Electives across SEAS graduate departments</li>
<li>Master's project / thesis option per SIE guidance</li>
</ul>"""
    return ""

def admissions_text(pid):
    if pid == "umich-aero-mse":
        return """<ul>
<li>Bachelor's degree equivalent to UMich BSE in Engineering; physics, applied physics, math, or other engineering backgrounds eligible</li>
<li>Strong undergraduate math and engineering preparation required</li>
<li>Recent admitted graduate applicants had combined GRE above 320 (V+Q) with high analytical writing (admission distribution, not a hard threshold)</li>
<li>GRE required for MSE applicants; not required for PhD or SUGS</li>
<li>TOEFL / IELTS (Rackham minimum; English-language degree exemption available)</li>
<li>Application materials: Rackham online application, transcripts, Academic SOP (~2 pages), Personal Statement (500-700 words), CV, 3 letters of recommendation (at least 2 from faculty)</li>
<li>Fall MSE deadline: January 15; Winter MSE deadline: October 7</li>
<li>Note: applicants without engineering background should submit FE exam mechanical discipline score</li>
</ul>"""
    if pid == "notre-msae":
        return """<ul>
<li>Bachelor's degree in aerospace or mechanical engineering, or similar field</li>
<li>GRE General Test optional</li>
<li>English proficiency: TOEFL / IELTS / Duolingo accepted</li>
<li>Application materials: online application, Statement of Intent, CV, 3 letters of recommendation, unofficial transcripts</li>
<li>Fall deadline: December 31; Spring deadline: October 15</li>
<li>Minimum 1 semester residency</li>
<li>Note: PhD program has full funding (stipend + tuition); MSAE has limited funding</li>
<li>Contact: Prof. Ryan McClarren, Director of Graduate Studies, rmcclarr@nd.edu</li>
</ul>"""
    if pid == "usc-aero-ms":
        return """<ul>
<li>Bachelor's degree in engineering or closely related field (Aerospace, Aeronautical, Mechanical, Mechatronics)</li>
<li>Non-related majors considered if strong preparation in computer engineering, linear systems, programming demonstrated</li>
<li>GRE not required for 2027 applications</li>
<li>English proficiency: TOEFL / IELTS (USC graduate standard)</li>
<li>Application materials: transcripts, resume/CV, Personal Statement</li>
<li>Letter of Recommendation: optional for Aerospace Engineering MS (2 required for Astronautical MS)</li>
<li>Fall scholarship consideration deadline: December 15; Fall final: January 15; Spring: October 15</li>
<li>Holistic review; meeting prerequisite courses does not guarantee admission</li>
</ul>"""
    if pid == "ucsd-se-ms":
        return """<ul>
<li>Bachelor's degree in engineering, physical sciences, or mathematics</li>
<li>Minimum upper-division GPA 3.0 on 4.0 scale</li>
<li>GRE permanently waived for MS applicants (submitted scores considered but not required; GRE not required for PhD but strongly recommended)</li>
<li>English proficiency: TOEFL iBT 85 / IELTS 7.0 / Duolingo 120 minimum</li>
<li>Application materials: 3 letters of recommendation (preferably 2 faculty), unofficial transcripts, SOP, CV, application fee</li>
<li>Institution code 4836 (for any submitted test scores)</li>
<li>Fall priority deadline: December 15</li>
<li>All materials submitted online; no hard copies until admitted</li>
</ul>"""
    if pid == "uva-se-ms":
        return """<ul>
<li>Baccalaureate degree from recognized college or university; engineering or applied science preferred; other backgrounds considered</li>
<li>B average (3.0) for admission to graduate studies</li>
<li>GRE optional (waived for 2026; submitted scores considered, institution code 5820)</li>
<li>English proficiency: TOEFL / IELTS (UVA Engineering standard; English for Academic Purposes summer program may be required)</li>
<li>Application materials: online application, essay, transcripts, 3 letters of recommendation, application fee</li>
<li>Fall financial-aid deadline: January 6; Spring deadline: September 30</li>
<li>Most accepted MS students receive GRA/GTA offers; default stipend $27,037.50/year plus tuition and health insurance</li>
<li>Note: VEO online M.E. and AMP M.E. are separate tracks (excluded as part-time/distance)</li>
</ul>"""
    return ""

# ---------- Write detail pages ----------
for p in programs:
    path = os.path.join(BASE, p["url"])
    with open(path, "w", encoding="utf-8") as f:
        f.write(detail_page(p))
    print(f"Wrote: {p['url']}")

# ---------- Append PROGRAMS ----------
with open(INDEX, "r", encoding="utf-8") as f:
    html = f.read()

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

new_block = ",\n".join(new_entries)

start = html.find("const PROGRAMS=[")
if start == -1:
    raise Exception("PROGRAMS array not found")
bracket_start = html.find("[", start)
depth = 1
i = bracket_start + 1
while i < len(html) and depth > 0:
    if html[i] == "[":
        depth += 1
    elif html[i] == "]":
        depth -= 1
    i += 1
insert_pos = i - 1
prev_char = html[insert_pos - 1].strip()
if prev_char == ",":
    html = html[:insert_pos] + "\n" + new_block + html[insert_pos:]
else:
    html = html[:insert_pos] + ",\n" + new_block + html[insert_pos:]

print(f"Appended {len(programs)} PROGRAMS entries")

# ---------- Append VD ----------
vd_start = html.find("const VERIFIED_DETAILS=new Set(")
if vd_start == -1:
    raise Exception("VD Set not found")
paren_start = html.find("(", vd_start)
depth = 1
i = paren_start + 1
while i < len(html) and depth > 0:
    if html[i] == "(":
        depth += 1
    elif html[i] == ")":
        depth -= 1
    i += 1
close_paren = i - 1
j = close_paren - 1
while j >= 0 and html[j] != "]":
    j -= 1
vd_entries = [f'"{p["url"]}"' for p in programs]
vd_block = ",\n".join(vd_entries)
prev_vd = html[j-1].strip()
if prev_vd == ",":
    html = html[:j] + "\n" + vd_block + html[j:]
else:
    html = html[:j] + ",\n" + vd_block + html[j:]

print(f"Appended {len(programs)} VD entries")

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

print(f"Done. File size: {len(html)}")
