import re, os

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

programs = [
    {
        "id": "notre-msme",
        "s": "notre",
        "n": "Mechanical Engineering MSME",
        "en": "Master of Science in Mechanical Engineering",
        "deg": "MSME",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years",
        "ddl": "Dec 31 (Fall); Oct 15 (Spring)",
        "lang": "TOEFL / IELTS / Duolingo",
        "test": "GRE optional",
        "tui": "待补",
        "url": "details/notre-msme.html"
    },
    {
        "id": "berkeley-cbe-pdp",
        "s": "berkeley",
        "n": "Chemical Biomolecular Engineering Professional MS",
        "en": "Master of Science in Chemical and Biomolecular Engineering (Product Development Program)",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "9 months (1 calendar year)",
        "ddl": "Jan 11, 2027 (Fall)",
        "lang": "TOEFL / IELTS (Berkeley graduate standard)",
        "test": "GRE not required",
        "tui": "待补",
        "url": "details/berkeley-cbe-pdp.html"
    },
    {
        "id": "ucla-aero-ms",
        "s": "ucla",
        "n": "Aerospace Engineering MS",
        "en": "Master of Science in Aerospace Engineering",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "2 years (6 quarters)",
        "ddl": "Dec 1, 2026 (Fall only)",
        "lang": "TOEFL / IELTS (UCLA graduate standard)",
        "test": "GRE General required",
        "tui": "待补",
        "url": "details/ucla-aero-ms.html"
    },
    {
        "id": "nyu-a3sr-ms",
        "s": "nyu",
        "n": "Applied Statistics for Social Science Research MS",
        "en": "Master of Science in Applied Statistics for Social Science Research",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (3-4 semesters)",
        "ddl": "Feb 1 (Fall)",
        "lang": "TOEFL / IELTS (NYU Steinhardt standard)",
        "test": "GRE required",
        "tui": "待补",
        "url": "details/nyu-a3sr-ms.html"
    },
    {
        "id": "ut-mscsm",
        "s": "ut",
        "n": "Sustainability Management MScSM",
        "en": "Master of Science in Sustainability Management",
        "deg": "MScSM",
        "lvl": "m",
        "stem": 0,
        "dur": "20 months (5 semesters: 4 academic + 1 work term)",
        "ddl": "待补",
        "lang": "TOEFL / IELTS (UofT SGS standard)",
        "test": "待补",
        "tui": "待补",
        "url": "details/ut-mscsm.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 == "notre-msme":
        return "The MS in Mechanical Engineering at University of Notre Dame Department of Aerospace and Mechanical Engineering (AME) combines coursework with research opportunities across flow physics and controls, plasma and high-temperature physics, laser and optical engineering, manufacturing engineering, nuclear engineering, and systems engineering. The program offers both thesis and non-thesis options. Note: AME PhD students receive full funding, but master's students are typically self-funded."
    if pid == "berkeley-cbe-pdp":
        return "The Product Development Program (PDP) at UC Berkeley Department of Chemical and Biomolecular Engineering is a 9-month professional Master's designed for STEM graduates ready to step into industry roles. The curriculum integrates advanced technical expertise with business strategy, including courses at the Haas School of Business (product management, finance, marketing). Students complete real-world capstone projects for corporate clients. Note: Berkeley's research-focused MS in Chemical Engineering is currently paused for admissions; PDP is the active professional master's option."
    if pid == "ucla-aero-ms":
        return "The MS in Aerospace Engineering at UCLA Samueli School of Engineering Department of Mechanical and Aerospace Engineering offers both thesis and comprehensive examination (capstone) plans. The program is flexible, with breadth requirements for students without ABET-accredited undergraduate degrees. Terminal MS students are normally admitted as master's students; conversion to PhD requires passing the PhD preliminary exam and finding a faculty sponsor."
    if pid == "nyu-a3sr-ms":
        return "The MS in Applied Statistics for Social Science Research (A3SR) at NYU Steinhardt School provides rigorous training in applied statistics for social, behavioral, and health science research. The variable-credit program (34-44 credits) offers four concentrations: General Applied Statistics, Computational Methods, Data Science for Social Impact, and Measurement/Methodology/Design. Students work closely with faculty on research in causal inference, demography, missing data, multilevel modeling, networks, and surveys."
    if pid == "ut-mscsm":
        return "The Master of Science in Sustainability Management (MScSM) at University of Toronto Mississauga (UTM) Institute for Management & Innovation is a 20-month interdisciplinary professional program integrating management, social science, and natural science to address sustainability challenges. Students specialize in either a management or science concentration. The program includes a mandatory 10-16 week internship/co-op work term, a major research paper, and an optional European exchange (University of Geneva, University of Copenhagen, Lund University)."
    return ""

def requirements_text(pid):
    if pid == "notre-msme":
        return """<ul>
<li>Total: 30 semester credit hours (typical for AME MS)</li>
<li><b>Thesis option:</b> coursework + thesis research under faculty advisor</li>
<li><b>Non-thesis option:</b> coursework + comprehensive exam</li>
<li>Research areas: flow physics & controls, plasma/high-temp physics, laser/optical engineering, manufacturing, nuclear engineering, systems engineering</li>
<li>Typical full-time completion: 1.5-2 years</li>
<li>Graduate Director: Ryan McClarren</li>
</ul>"""
    if pid == "berkeley-cbe-pdp":
        return """<ul>
<li>Total: 28 semester units</li>
<li>At least 18 units from letter-graded courses</li>
<li>Minimum 12 units from graduate-level (200 series) courses</li>
<li>Industry specialization declared at entrance (biotech, microelectronics, nanoscience, consumer products)</li>
<li>Real-world capstone field study assignment with corporate clients</li>
<li>No thesis required</li>
<li>9 months / 1 calendar year to complete</li>
</ul>"""
    if pid == "ucla-aero-ms":
        return """<ul>
<li>Total: 9 courses / 36 units</li>
<li>At least 5 courses (20 units) must be graduate (200-level) courses</li>
<li><b>Thesis plan:</b> 7 formal courses (at least 4 from 200 series) + 2 units MAE 598 thesis research</li>
<li><b>Comprehensive exam (capstone) plan:</b> 9 formal courses; no 500-series units may count toward minimum</li>
<li>Breadth requirement: 3 courses from 4 categories (for non-ABET BS): MAE 154A/B/S, 150B/P, 155/166A/169A, 161A/171A</li>
<li>All requirements must be completed within normative time</li>
<li>No lower-division courses may count toward graduate degree</li>
</ul>"""
    if pid == "nyu-a3sr-ms":
        return """<ul>
<li>Total: 34-44 variable credits (fewer for students with prior statistical training)</li>
<li>Required courses: ~23 credits (foundations, statistical inference, GLM, causal inference, multivariate, multilevel modeling)</li>
<li>Concentration: 8 credits (choose one of 4 tracks)</li>
<li>Electives: at least 8 credits (4 from APSTA-GE, plus unrestricted electives)</li>
<li>Statistical consulting research seminar + internship required</li>
<li>Full-time: 3-4 semesters</li>
<li>Part-time permitted (up to 6 years to complete)</li>
</ul>"""
    if pid == "ut-mscsm":
        return """<ul>
<li>Total: 20 months / 5 semesters (4 academic + 1 work term)</li>
<li>11 required core courses</li>
<li>5 elective courses (management or science concentration)</li>
<li>10-16 week mandatory internship/co-op work term</li>
<li>Major research paper (SSM 1100Y)</li>
<li>Capstone course: The Sustainable Enterprise (SSM 1090H)</li>
<li>Mandatory Orientation + Boot Camp (2 weeks, late August)</li>
<li>Optional European exchange: University of Geneva, University of Copenhagen, Lund University</li>
</ul>"""
    return ""

def curriculum_text(pid):
    if pid == "notre-msme":
        return """<ul>
<li>Research areas: flow physics & controls, plasma & high-temperature physics, laser & optical engineering, manufacturing engineering, nuclear engineering, systems engineering</li>
<li>State-of-the-art facilities and leading research techniques</li>
<li>Students and faculty publish regularly in leading engineering publications</li>
<li>Cross-departmental electives available</li>
</ul>"""
    if pid == "berkeley-cbe-pdp":
        return """<ul>
<li>Technical core: advanced chemical & biomolecular engineering (200-series)</li>
<li>Business/management: Haas School of Business courses in product management, finance, marketing</li>
<li>Industry specialization tracks: biotechnology, microelectronics, nanoscience, consumer products</li>
<li>Capstone: collaborative team project solving product development challenges for real corporate clients</li>
<li>80% of graduates secure top roles within 6 months</li>
</ul>"""
    if pid == "ucla-aero-ms":
        return """<ul>
<li>Established areas: aerodynamics, propulsion, structures, controls, spacecraft dynamics, aerospace materials</li>
<li>MAE 297 - graduate seminar series</li>
<li>MAE 598 - research units (thesis plan)</li>
<li>Breadth courses: MAE 154 (Aerodynamics), 150 (Propulsion), 155/166/169 (Structures/Controls), 161/171 (Materials)</li>
<li>Electives may be chosen across Samueli School of Engineering departments</li>
</ul>"""
    if pid == "nyu-a3sr-ms":
        return """<ul>
<li>APSTA-GE 2001/2351 - Foundations of Applied Statistics (place-out eligible)</li>
<li>APSTA-GE 2003 / STAT-GB 2301 - Intermediate Quantitative Methods / Regression & Multivariate</li>
<li>APSTA-GE 2004 - Topics in Multivariate Analysis</li>
<li>APSTA-GE 2012 - Causal Inference</li>
<li>APSTA-GE 2044 - Generalized Linear Models and Extensions</li>
<li>APSTA-GE 2040/2042 - Multilevel Modeling / Growth Curve</li>
<li><b>Concentrations:</b>
  <ul>
  <li>General Applied Statistics: 3 APSTA-GE electives (8 credits)</li>
  <li>Computational Methods: ML (2011) + Statistical Inference Frequentist (2122) + 2 of (Bayesian Inference / Missing Data / Education Data Science Practicum)</li>
  <li>Data Science for Social Impact: ML (2011) + Ethics of Data Science (2062) + Data Science Translation (2355)</li>
  </ul>
</li>
</ul>"""
    if pid == "ut-mscsm":
        return """<ul>
<li><b>First year Fall:</b> SSM 1010Y Principles of Sustainability Management, SSM 1020H Decision Making, SSM 1050H Ecosystem Science, SSM 1060H Managing Sustainable Organizations</li>
<li><b>First year Winter:</b> SSM 1030H Environmental Science, SSM 1040H Managerial Economics, SSM 1070H Sustainability Law & Policy, SSM 1080H Strategies for Sustainability Management</li>
<li><b>First year Spring/Summer:</b> SSM 1120H Social Dimensions of Sustainability + Internship/Co-op placement (10-16 weeks)</li>
<li><b>Second year:</b> SSM 1100Y Research Paper, SSM 1090H Capstone - The Sustainable Enterprise, 5 electives</li>
<li>Electives: management or science concentration; may be taken across UofT campuses</li>
</ul>"""
    return ""

def admissions_text(pid):
    if pid == "notre-msme":
        return """<ul>
<li>Undergraduate degree in mechanical or aerospace engineering or similar field</li>
<li>GRE General Test optional</li>
<li>TOEFL / IELTS / Duolingo (non-native English speakers)</li>
<li>Application materials: CV, statement of intent, 3 letters of recommendation, transcripts</li>
<li>Deadlines: Fall Dec 31; Spring Oct 15</li>
<li>No departmental financial support for master's students; typically self-funded</li>
</ul>"""
    if pid == "berkeley-cbe-pdp":
        return """<ul>
<li>Bachelor's degree in STEM (chemical engineering or related field)</li>
<li>Minimum GPA 3.0 (Berkeley Graduate Division minimum)</li>
<li>GRE not required</li>
<li>TOEFL / IELTS (Berkeley graduate standard for international students)</li>
<li>Application materials: transcripts, SOP, Personal History Statement, letters of recommendation</li>
<li>Deadline: January 11, 2027 (Fall admission only)</li>
<li>Contact: cbepdp@berkeley.edu</li>
</ul>"""
    if pid == "ucla-aero-ms":
        return """<ul>
<li>B.S. degree in engineering or related field</li>
<li>Minimum cumulative GPA 3.0 (UCLA Graduate Division requirement)</li>
<li>GRE General Test required</li>
<li>TOEFL / IELTS (UCLA graduate standard)</li>
<li>Application materials: SOP, personal statement, CV/resume, 3 letters of recommendation</li>
<li>Deadline: December 1, 2026 (Fall admission only)</li>
<li>Terminal MS students normally admitted as master's; PhD conversion requires preliminary exam + faculty sponsor</li>
</ul>"""
    if pid == "nyu-a3sr-ms":
        return """<ul>
<li>Bachelor's degree with quantitative background (math, statistics, CS, or quantitative social science)</li>
<li>Coursework in calculus, linear algebra, probability, statistics</li>
<li>GRE required</li>
<li>TOEFL / IELTS (NYU Steinhardt standard)</li>
<li>Application materials: transcripts, SOP, CV, letters of recommendation</li>
<li>Deadline: February 1 (Fall admission)</li>
<li>Full-time or part-time enrollment available</li>
</ul>"""
    if pid == "ut-mscsm":
        return """<ul>
<li>Bachelor's degree in management, social science, natural science, engineering, or related field</li>
<li>Designed for diverse backgrounds; not limited to sustainability majors</li>
<li>Full-time only (20-month program)</li>
<li>Mandatory Orientation + Boot Camp (2 weeks, late August)</li>
<li>Contact: mscsm.utm@utoronto.ca / (905) 569-5803</li>
<li>Location: UTM Innovation Complex, Mississauga, Ontario</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)

# Find end of PROGRAMS array
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")

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

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