import re, os

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

programs = [
    {
        "id": "ucsd-mae-ms",
        "s": "ucsd",
        "n": "Mechanical and Aerospace Engineering MS",
        "en": "Master of Science in Mechanical and Aerospace Engineering",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (36 units, min 3 quarters)",
        "ddl": "Dec 15, 2026 (Fall 2027 priority)",
        "lang": "TOEFL / IELTS (English-language degree waiver available)",
        "test": "GRE required per UCSD catalog",
        "tui": "待补",
        "url": "details/ucsd-mae-ms.html"
    },
    {
        "id": "umich-robotics-ms",
        "s": "umich",
        "n": "Robotics MS",
        "en": "Master of Science in Robotics",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (Rackham graduate)",
        "ddl": "Jan 15, 2027 (Fall only)",
        "lang": "TOEFL / IELTS / MET / ECPE (Rackham minimum)",
        "test": "GRE optional for MS",
        "tui": "待补",
        "url": "details/umich-robotics-ms.html"
    },
    {
        "id": "notre-msce",
        "s": "notre",
        "n": "Civil Engineering MSCE",
        "en": "Master of Science in Civil Engineering",
        "deg": "MSCE",
        "lvl": "m",
        "stem": 1,
        "dur": "2-3 years (30 credits, research-based)",
        "ddl": "Jan 1, 2027 (Fall); Oct 1 (Spring)",
        "lang": "TOEFL / IELTS / Duolingo",
        "test": "GRE optional",
        "tui": "待补",
        "url": "details/notre-msce.html"
    },
    {
        "id": "usc-apmath-ms",
        "s": "usc",
        "n": "Applied Mathematics MS",
        "en": "Master of Science in Applied Mathematics",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (30 units)",
        "ddl": "Dec 15, 2026 (Fall); Oct 15 (Spring)",
        "lang": "TOEFL / IELTS (USC graduate standard)",
        "test": "GRE General Test required per USC catalog",
        "tui": "待补",
        "url": "details/usc-apmath-ms.html"
    },
    {
        "id": "umich-bme-ms",
        "s": "umich",
        "n": "Biomedical Engineering MSE",
        "en": "Master of Science in Engineering - Biomedical Engineering",
        "deg": "MSE",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (30 credits)",
        "ddl": "Jan 15, 2027 (Fall only)",
        "lang": "TOEFL / IELTS (Rackham minimum)",
        "test": "GRE not required (not accepted)",
        "tui": "待补",
        "url": "details/umich-bme-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 == "ucsd-mae-ms":
        return "The Master of Science in Mechanical and Aerospace Engineering at UC San Diego Jacobs School of Engineering / Department of Mechanical and Aerospace Engineering (MAE) is a research-oriented terminal master's program. Students select a specialization among Mechanical Engineering, Aerospace Engineering, Engineering Physics, and related tracks. The program combines rigorous coursework with a Comprehensive Examination requirement and an optional thesis plan (Plan I). Admission is competitive with a typical admitted GPA of 3.5 or higher on a 4.0 scale."
    if pid == "umich-robotics-ms":
        return "The Master of Science in Robotics at University of Michigan Rackham Graduate School / Robotics Institute is a research-oriented terminal master's program. The Robotics Institute is one of the largest academic robotics programs in the US, spanning perception, control, machine learning, motion planning, human-robot interaction, legged locomotion, autonomous systems, and medical robotics. The MS admits Fall only and is distinct from the PhD track (PhD deadline Dec 1)."
    if pid == "notre-msce":
        return "The Master of Science in Civil Engineering (MSCE) at University of Notre Dame College of Engineering / Department of Civil and Environmental Engineering and Earth Sciences (CEES) is a research-based thesis program. Students pursue research in environmental engineering, environmental fluid dynamics, environmental geosciences, and structural engineering. The department also offers parallel MSEnvE (Environmental Engineering) and MSES (Earth Sciences) tracks."
    if pid == "usc-apmath-ms":
        return "The Master of Science in Applied Mathematics at USC Dana and David Dornsife College of Letters, Arts and Sciences / Department of Mathematics is a quantitative terminal master's program bridging pure mathematics foundations with applications in industry, data science, and engineering. The program requires a strong undergraduate background in real analysis and linear algebra and serves as preparation for PhD study or industry analyst roles."
    if pid == "umich-bme-ms":
        return "The Master of Science in Engineering (MSE) in Biomedical Engineering at University of Michigan Rackham Graduate School / Department of Biomedical Engineering is a research-oriented terminal master's program. Students select one of five concentrations and may complete directed research credits under a BME faculty advisor. The program is distinct from the AMPED professional MEng (Advanced Medical Product Engineering and Development) track."
    return ""

def requirements_text(pid):
    if pid == "ucsd-mae-ms":
        return """<ul>
<li>Total: 36 units of graduate coursework</li>
<li>Minimum residence: 6 units per quarter for at least 3 quarters</li>
<li>Minimum cumulative GPA 3.0 (B); typical admitted GPA 3.5+ (admission distribution, not a hard threshold)</li>
<li>Comprehensive Examination: pass at least 3 examination components within chosen specialization</li>
<li>Plan I (thesis): thesis + oral defense with faculty advisor and two committee members; Plan II (coursework): comprehensive exam</li>
<li>All courses letter-graded (except MAE 299 research units S/U)</li>
<li>Advance to candidacy by week 3 of intended graduation quarter</li>
</ul>"""
    if pid == "umich-robotics-ms":
        return """<ul>
<li>Total: Rackham MS credit hours (typically 30 credits)</li>
<li>Minimum cumulative Rackham GPA 3.0 (B) to graduate</li>
<li>Fall admission only for external applicants (application available late August)</li>
<li>Fall deadline: January 15 (MS); December 1 (PhD)</li>
<li>SUGS track (UMich BSE students only): Winter deadline October 1 / Fall deadline January 15</li>
<li>Dual-degree applicants: primary program must not already offer a robotics option (e.g., ECE / MECHENG dual degree not admitted)</li>
</ul>"""
    if pid == "notre-msce":
        return """<ul>
<li>Total: 30 credits (16-24 credits coursework + thesis research credits)</li>
<li>Written thesis defense required in front of advisor + two committee members</li>
<li>Typical completion: 2-3 years</li>
<li>Minimum residency: 1 semester</li>
<li>Research areas: environmental engineering, environmental fluid dynamics, environmental geosciences, structural engineering</li>
<li>Fall admission deadline: January 1; Spring admission deadline: October 1</li>
<li>Open to students holding an undergraduate engineering or physical-sciences degree</li>
</ul>"""
    if pid == "usc-apmath-ms":
        return """<ul>
<li>Total: 30 units of graduate coursework (USC Dornsife MS standard)</li>
<li>Minimum cumulative GPA 3.0 on all USC graduate units attempted</li>
<li>Minimum grade of C (2.0) required for graduate credit; C- or below not accepted</li>
<li>Continuous enrollment required each Fall and Spring until degree completion</li>
<li>Prerequisites: one semester real analysis / advanced calculus, one semester upper-division linear algebra</li>
<li>Coursework at 400-level or higher; thesis / exam options per department handbook</li>
</ul>"""
    if pid == "umich-bme-ms":
        return """<ul>
<li>Total: 30 credits of coursework</li>
<li>Required: 1 math course (approved list), 1 stats course (approved list), 2 BME graduate seminars, 1 experiential course, 1 core course by concentration, technical electives</li>
<li>Bioninstrumentation course required if not completed during undergraduate</li>
<li>Five concentrations available (select at start of program)</li>
<li>Directed Research credits available via BIOMEDE 590 under faculty advisor</li>
<li>Typical completion: 1.5-2 years</li>
<li>Note: students who already hold an MS in BME from another institution cannot apply to this MS</li>
</ul>"""
    return ""

def curriculum_text(pid):
    if pid == "ucsd-mae-ms":
        return """<ul>
<li>Core MS program: customized curriculum across MAE technical electives</li>
<li>Specializations: Mechanical Engineering (MC81), Aerospace Engineering, Engineering Physics, Fluid Mechanics, Materials</li>
<li>Five courses per specialization carry a Comprehensive Examination component</li>
<li>Recommended full-time enrollment: 12 units per quarter</li>
<li>Plan I thesis: MAE 299 research units + oral defense</li>
<li>Electives across Jacobs School of Engineering and Graduate Division</li>
</ul>"""
    if pid == "umich-robotics-ms":
        return """<ul>
<li>Core robotics graduate coursework: perception, control, motion planning, machine learning for robotics</li>
<li>Research areas: legged locomotion, autonomous ground/air vehicles, human-robot interaction, medical robotics, robot learning, computer vision</li>
<li>Technical electives across EECS, ME, Aerospace Engineering, and other Rackham departments</li>
<li>Faculty-mentored research optional for thesis-track students</li>
<li>Graduate seminar series</li>
<li>Advising: assigned by Robotics Graduate Office</li>
</ul>"""
    if pid == "notre-msce":
        return """<ul>
<li>Core coursework in chosen research area (environmental / structural / geosciences / fluid dynamics)</li>
<li>Graduate seminar series</li>
<li>Thesis research credits under faculty advisor</li>
<li>Interdisciplinary electives across College of Engineering and Science</li>
<li>Access to state-of-the-art laboratories and computing facilities</li>
<li>Final oral defense of written thesis</li>
</ul>"""
    if pid == "usc-apmath-ms":
        return """<ul>
<li>Foundations: real analysis (MATH 425a/425b), upper-division linear algebra (MATH 471)</li>
<li>Core: advanced applied mathematics, numerical analysis, mathematical modeling, optimization</li>
<li>Electives: probability, statistics, scientific computing, differential equations, mathematical finance</li>
<li>Research / thesis option for students preparing for PhD study</li>
<li>Department handbook specifies 30-unit distribution across breadth and depth</li>
</ul>"""
    if pid == "umich-bme-ms":
        return """<ul>
<li>Required: 1 math course, 1 statistics course (approved Rackham lists)</li>
<li>Required: 2 BME graduate seminars</li>
<li>Required: 1 experiential course (approved list)</li>
<li>Required: 1 core course selected based on concentration</li>
<li>Five concentrations: e.g., biomedical imaging, bioelectrics and neuroengineering, cell and tissue engineering, biomechanics, systems biomechanics (exact list per current BME handbook)</li>
<li>Technical electives complete the 30-credit plan</li>
<li>Directed Research (BIOMEDE 590) optional under BME faculty advisor</li>
</ul>"""
    return ""

def admissions_text(pid):
    if pid == "ucsd-mae-ms":
        return """<ul>
<li>Bachelor's degree in engineering, physics, mathematics, or closely related quantitative field</li>
<li>Minimum GPA 3.0 on 4.0 scale; typical admitted GPA 3.5+ (admission distribution, not a hard threshold)</li>
<li>GRE General Test required per UCSD catalog (current department policy to verify on MAE admissions page)</li>
<li>English proficiency: TOEFL / IELTS required for non-native English speakers; English-language degree waiver available per IAU WHED criterion</li>
<li>Three letters of recommendation from individuals who can attest to academic and professional competence</li>
<li>Application materials: transcripts, SOP, personal statement, CV, letters of recommendation</li>
<li>No undergraduate engineering degree required, but strong math and physics background expected</li>
<li>Fall admission priority deadline: December 15</li>
</ul>"""
    if pid == "umich-robotics-ms":
        return """<ul>
<li>Bachelor's degree in engineering, computer science, or related quantitative field</li>
<li>GRE optional for MS applicants (submitted scores considered but not required)</li>
<li>English proficiency: TOEFL / MET / ECPE / IELTS (Rackham minimum); English-language bachelor's degree exemption available</li>
<li>Test scores valid for two years from test date</li>
<li>Application materials: Rackham online application, transcripts, Academic SOP, Personal Statement, CV, 3 letters of recommendation</li>
<li>Fall admission only; deadline January 15, 2027 (application available late August 2026)</li>
<li>Dual-degree not allowed if home program already has a robotics option</li>
<li>International students must arrange F-1 visa / OPT through International Center</li>
</ul>"""
    if pid == "notre-msce":
        return """<ul>
<li>Bachelor's degree in any engineering or physical sciences 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 (official transcripts upon enrollment)</li>
<li>Fall deadline: January 1; Spring deadline: October 1</li>
<li>Minimum cumulative GPA 3.0 throughout graduate degree</li>
<li>Contact: ceeesdgs@nd.edu; Director of Graduate Studies: Prof. Alexandros Taflanidis</li>
</ul>"""
    if pid == "usc-apmath-ms":
        return """<ul>
<li>Bachelor's degree with substantial undergraduate mathematics background</li>
<li>Required prerequisites: one semester real analysis or advanced calculus, one semester upper-division linear algebra</li>
<li>Minimum undergraduate GPA 3.0; PhD cycle typical admitted GPA ~3.89 (admission distribution, not a hard threshold for MS)</li>
<li>GRE General Test required per USC catalog (current department policy to verify on Dornsife admissions page)</li>
<li>English proficiency: TOEFL / IELTS (USC graduate standard)</li>
<li>Three letters of recommendation, ideally from mathematics faculty who have taught the applicant for at least one semester</li>
<li>Fall deadline: December 15; Spring deadline: October 15 (applications open August 1)</li>
<li>Note: students enrolled in the MS must complete the PhD screening procedure before being considered for the PhD program</li>
</ul>"""
    if pid == "umich-bme-ms":
        return """<ul>
<li>Bachelor's degree in engineering or the physical sciences (physics, polymer science, applied math); quantitative life sciences backgrounds considered</li>
<li>Recommended minimum GPA 3.2 (4.0 scale) for Master's applicants; typical admitted GPA ~3.5 (admission distribution, not a hard threshold)</li>
<li>Typical undergraduate preparation: biology with lab, 2 terms physics, mathematics through ODE, minimum 4 engineering courses</li>
<li>GRE not required (and not accepted) for MS and PhD admissions</li>
<li>TOEFL / IELTS (Rackham minimum); English-language degree waiver available</li>
<li>Application materials: Rackham online application, transcripts, SOP, Personal Statement, CV, 3 letters of recommendation</li>
<li>Fall admission only; deadline January 15, 2027</li>
<li>Note: students who already hold an MS in BME from another institution cannot apply to this MS</li>
<li>AMPED professional MEng is a separate track for medtech industry preparation</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)}")
