import re, os

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

programs = [
    {
        "id": "berkeley-maiml",
        "s": "berkeley",
        "n": "Master of AI and Machine Learning (MAIML)",
        "en": "Master of Artificial Intelligence and Machine Learning",
        "deg": "MAIML",
        "lvl": "m",
        "stem": 1,
        "dur": "2 semesters (Fall + Spring, 1 academic year)",
        "ddl": "Jan 11, 2027 (Fall 2027 first cohort)",
        "lang": "TOEFL / IELTS (Berkeley graduate standard)",
        "test": "GRE optional",
        "tui": "待补",
        "url": "details/berkeley-maiml.html"
    },
    {
        "id": "berkeley-macss",
        "s": "berkeley",
        "n": "Master of Computational Social Science (MaCSS)",
        "en": "Master of Computational Social Science",
        "deg": "MACSS",
        "lvl": "m",
        "stem": 0,
        "dur": "1 year (Summer start)",
        "ddl": "Jan 6, 2027 (Summer 2027)",
        "lang": "TOEFL / IELTS (Berkeley graduate standard)",
        "test": "GRE not required",
        "tui": "待补",
        "url": "details/berkeley-macss.html"
    },
    {
        "id": "ut-mmpa",
        "s": "ut",
        "n": "Management and Professional Accounting MMPA",
        "en": "Master of Management and Professional Accounting",
        "deg": "MMPA",
        "lvl": "m",
        "stem": 0,
        "dur": "27 months (7 sessions full-time)",
        "ddl": "Jan 31, 2027",
        "lang": "TOEFL 100 (W22/S22) / IELTS 7.0 (6.5 each)",
        "test": "GMAT 570 (verbal 46%, quant 46%, AWA 4.0); waivers available; GRE not accepted",
        "tui": "待补",
        "url": "details/ut-mmpa.html"
    },
    {
        "id": "umich-ece-ms",
        "s": "umich",
        "n": "Electrical and Computer Engineering MS",
        "en": "Master of Science in Electrical and Computer Engineering",
        "deg": "MSE",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (30 credits)",
        "ddl": "Jan 15, 2027 (Fall)",
        "lang": "TOEFL 84 (Rackham minimum)",
        "test": "GRE required for international (non-US bachelor's); US degree holders optional",
        "tui": "待补",
        "url": "details/umich-ece-ms.html"
    },
    {
        "id": "umich-me-mse",
        "s": "umich",
        "n": "Mechanical Engineering MSE",
        "en": "Master of Science in Engineering - Mechanical Engineering",
        "deg": "MSE",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years (30 credits)",
        "ddl": "Jan 15, 2027 (Fall only)",
        "lang": "TOEFL 84 (Rackham minimum)",
        "test": "GRE optional (Fall 2027)",
        "tui": "待补",
        "url": "details/umich-me-mse.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 == "berkeley-maiml":
        return "The Master of Artificial Intelligence and Machine Learning (MAIML) at UC Berkeley College of Computing, Data Science, and Society (CDSS) is a two-semester professional program launching Fall 2027 (first cohort). Designed for STEM graduates targeting industry ML engineer and AI researcher roles, the curriculum is co-taught by faculty from Electrical Engineering and Computer Sciences (EECS) and Statistics. The program includes a signature two-day Silicon Valley immersion between semesters. Students must pass a comprehensive examination to graduate."
    if pid == "berkeley-macss":
        return "The Master of Computational Social Science (MaCSS) at UC Berkeley College of Letters and Science is a one-year in-person professional degree integrating computing tools, statistical data analysis, and social science theory. The program is designed specifically for students with a social science background; STEM (data science/CS) majors are not eligible and should consider MIDS or MIMS instead. Graduates take data analyst roles in business, government, and nonprofits. The program starts in Summer Session."
    if pid == "ut-mmpa":
        return "The Master of Management and Professional Accounting (MMPA) at University of Toronto Mississauga Institute for Management & Innovation is a 27-month full-time professional accounting program covering seven sessions of study. The program prepares students for the Canadian CPA accreditation pathway and includes practical co-op/integrated experience. It offers both a one-year stream (for students with an accounting specialist undergraduate degree) and a two-year stream (for non-accounting backgrounds)."
    if pid == "umich-ece-ms":
        return "The Master of Science in Electrical and Computer Engineering at University of Michigan Rackham Graduate School / Department of Electrical Engineering and Computer Science is a research-oriented terminal master's program. The ECE department offers MS and MEng tracks; the MS (MSE) track typically includes coursework plus optional research. Students may specialize in areas such as applied electromagnetics, circuits/computing, communications/signal processing, controls, embedded systems, MEMS, optics, photonics, and solid-state devices."
    if pid == "umich-me-mse":
        return "The Master of Science in Engineering (MSE) in Mechanical Engineering at University of Michigan Rackham Graduate School / Department of Mechanical Engineering offers three program options: (1) coursework only, (2) coursework with an individual research project, and (3) coursework with a thesis. Research areas include automotive, biomechanics and biosystems, controls, design, dynamics and vibrations, energy, fluids, manufacturing, mechanics and materials, mechatronics, robotics, micro/nano engineering, and thermal sciences."
    return ""

def requirements_text(pid):
    if pid == "berkeley-maiml":
        return """<ul>
<li>Total: 2 semesters (Fall + Spring)</li>
<li>Core coursework in data science, machine learning, probability, statistical inference, AI ethics</li>
<li>Specialized electives in ML/AI systems</li>
<li>Two-day Silicon Valley immersion between Fall and Spring semesters</li>
<li>Comprehensive examination required to graduate</li>
<li>Full-time in-person only</li>
<li>First cohort: Fall 2027</li>
</ul>"""
    if pid == "berkeley-macss":
        return """<ul>
<li>Total: 1 year / 3 semesters (Summer start + Fall + Spring)</li>
<li>Curriculum integrates computing tools, statistical approaches to data analysis, and social science theory</li>
<li>Quantitative skills bridge curriculum at start of Summer Session</li>
<li>Capstone / applied project expected</li>
<li>Full-time in-person only, based in Berkeley</li>
<li>Admission is restricted to social-science-background students; STEM majors are not eligible</li>
</ul>"""
    if pid == "ut-mmpa":
        return """<ul>
<li>Total: 27 months / 7 sessions full-time</li>
<li>Two streams: 1-year stream (for accounting specialist undergrads) and 2-year stream (for other backgrounds)</li>
<li>Co-op / integrated practical experience required</li>
<li>Curriculum aligned with Canadian CPA accreditation pathway</li>
<li>Mid-B average (73-76% / 3.0 GPA) required throughout graduate degree</li>
<li>Two letters of reference, one 500-word essay, and by-invitation interview required</li>
</ul>"""
    if pid == "umich-ece-ms":
        return """<ul>
<li>Total: 30 credit hours (typical Rackham MS)</li>
<li>Coursework plus optional research / thesis plan</li>
<li>Technical areas: applied electromagnetics, circuits/computing, communications/signal processing, controls, embedded systems, MEMS, optics/photonics, solid-state devices</li>
<li>Typical completion: 1.5-2 years</li>
<li>Fall admission only for external applicants (Winter admission is for current UMich students only)</li>
<li>Note: students who already hold an MS or PhD in ECE from another institution cannot apply to the same degree at UMich</li>
</ul>"""
    if pid == "umich-me-mse":
        return """<ul>
<li>Total: 30 credit hours</li>
<li>Three options:
  <ul>
  <li>Option 1: coursework only</li>
  <li>Option 2: coursework + individual research project</li>
  <li>Option 3: coursework + MSE thesis</li>
  </ul>
</li>
<li>Research areas: automotive, biomechanics/biosystems, controls, design, dynamics/vibrations, energy, fluids, manufacturing, mechanics/materials, mechatronics, robotics, micro/nano engineering, multi-scale computation, thermal sciences</li>
<li>Fall admission only for external applicants</li>
<li>Cumulative GPA must be maintained throughout the program</li>
</ul>"""
    return ""

def curriculum_text(pid):
    if pid == "berkeley-maiml":
        return """<ul>
<li>Foundations: data science, probability, statistical inference, linear algebra, multivariate calculus</li>
<li>Core: machine learning, deep learning, AI ethics, computational foundations</li>
<li>Electives: specialized ML/AI systems courses from EECS and Statistics</li>
<li>Silicon Valley immersion (2 days, between semesters): bridges academic learning with real-world industry practice</li>
<li>Comprehensive examination at end of Spring semester</li>
<li>Taught by EECS and Statistics faculty within CDSS</li>
</ul>"""
    if pid == "berkeley-macss":
        return """<ul>
<li>Summer Session: quantitative skills bridge (computing, statistics, data analysis fundamentals)</li>
<li>Fall: core computational methods + statistical approaches to social science data</li>
<li>Spring: social science theory electives + applied capstone project</li>
<li>Topics: inequality/exclusion, healthcare access, climate change, social structures, human behavior</li>
<li>Electives across social science departments (Sociology, Political Science, Economics, etc.)</li>
<li>Career development workshops: interviewing, networking, resume</li>
</ul>"""
    if pid == "ut-mmpa":
        return """<ul>
<li>Accounting core: financial accounting, management accounting, auditing, taxation</li>
<li>Business core: finance, economics, strategy, organizational behavior</li>
<li>Integrated practical experience / co-op term</li>
<li>CPA-aligned curriculum covering all Competency Map areas</li>
<li>Leadership and communication skills development</li>
<li>Elective topics for specialized accounting practice</li>
</ul>"""
    if pid == "umich-ece-ms":
        return """<ul>
<li>Core ECE graduate courses in chosen technical area</li>
<li>Technical areas include: applied electromagnetics, VLSI/circuits, communications/signal processing, control systems, embedded systems, MEMS, optics/photonics, solid-state devices, computer vision</li>
<li>Electives across CSE, applied physics, and related engineering departments</li>
<li>Optional research credits under faculty advisor</li>
<li>Graduate seminar series</li>
</ul>"""
    if pid == "umich-me-mse":
        return """<ul>
<li>Core mechanical engineering graduate coursework</li>
<li>Research areas: automotive, biomechanics/biosystems, controls, design, dynamics/vibrations, energy, fluids, manufacturing, mechanics/materials, mechatronics, robotics, micro/nano engineering, thermal sciences</li>
<li>Option 2: individual research project credits under faculty advisor</li>
<li>Option 3: thesis credits + final oral defense</li>
<li>Electives across Rackham graduate departments</li>
</ul>"""
    return ""

def admissions_text(pid):
    if pid == "berkeley-maiml":
        return """<ul>
<li>Bachelor's degree in CS, Data Science, Statistics, Applied Mathematics, or closely related STEM field</li>
<li>Minimum GPA 3.0 (B) on 4.0 scale</li>
<li>Prerequisites: object-oriented programming, data structures/algorithms, linear algebra, statistics, probability, software engineering, multivariate calculus</li>
<li>GRE optional (may be submitted to demonstrate quantitative ability)</li>
<li>TOEFL / IELTS (Berkeley graduate standard for international students)</li>
<li>Application materials: transcripts, SOP, Personal History Statement, resume (max 2 pages), 3 letters of recommendation</li>
<li>Deadline: January 11, 2027 (Fall 2027 first cohort)</li>
<li>Merit and need-based scholarships available</li>
<li>Contact: maiml_cdss@berkeley.edu</li>
</ul>"""
    if pid == "berkeley-macss":
        return """<ul>
<li>Bachelor's degree in a social science field (STEM/CS/Data Science majors not eligible)</li>
<li>Quantitative skills expected but bridge curriculum provided at start</li>
<li>GRE not required</li>
<li>TOEFL / IELTS (Berkeley graduate standard; English-language degree waiver available per Berkeley policy)</li>
<li>Application materials: online application, transcripts, personal statement, quantitative statement, resume, 2 letters of recommendation, video/audio submission, SOP</li>
<li>Deadline: January 6, 2027 (Summer 2027 start)</li>
<li>Email: macss@berkeley.edu</li>
</ul>"""
    if pid == "ut-mmpa":
        return """<ul>
<li>4-year bachelor's degree (3-year degree accepted with a qualifying year of senior-level courses)</li>
<li>Minimum mid-B average (73-76% / 3.0 GPA) in final undergraduate year</li>
<li>GMAT required: total 570, verbal 46%, quant 46%, AWA 4.0 (IR no minimum); GRE not accepted</li>
<li>GMAT waiver: 4-year degree from accredited North American university, or UTM/Rotman/UTSc BCom/BBA accounting specialist graduates</li>
<li>TOEFL 100 (W22/S22) / IELTS 7.0 (6.5 each) / MELAB 85 / COPE 86</li>
<li>Two letters of reference, one 500-word essay, by-invitation interview</li>
<li>Application fee: CDN$355</li>
<li>Deadline: January 31 (applications Sep 1 - Jan 31)</li>
<li>International students require Study Permit + Co-op Work Permit</li>
</ul>"""
    if pid == "umich-ece-ms":
        return """<ul>
<li>Bachelor's degree in engineering, physics, mathematics, or related field</li>
<li>Recommended minimum GPA 3.5 on 4.0 scale (admission distribution, not a hard threshold)</li>
<li>GRE required for applicants with non-US bachelor's degrees; US bachelor's degree holders may submit optionally (average admitted score ~324, upper 50th percentile)</li>
<li>TOEFL minimum 84 (Rackham); English-language bachelor's degree exemption available</li>
<li>Application materials: transcripts, Academic Statement of Purpose (1-3 pages), Personal Statement, 3 letters of recommendation, CV</li>
<li>Deadline: January 15, 2027 (Fall admission)</li>
<li>Note: students who already hold an MS or PhD in ECE from another institution cannot apply to the same degree at UMich</li>
</ul>"""
    if pid == "umich-me-mse":
        return """<ul>
<li>Bachelor's degree in mechanical engineering or closely related field</li>
<li>No specific minimum GPA required (admissions distribution, not a hard threshold)</li>
<li>GRE optional for Fall 2027 (submitted scores will be considered)</li>
<li>TOEFL minimum 84 (Rackham, institution code 1839); English-language degree exemption available</li>
<li>Application materials: transcripts, SOP (1-3 pages), Personal Statement (max 500 words), 3 letters of recommendation</li>
<li>Deadline: January 15, 2027 (Fall admission only for external applicants)</li>
<li>Email: me-grad-application@umich.edu</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)}")
