import re, os

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

# ---------- 5 new programs ----------
programs = [
    {
        "id": "usc-stats-ms",
        "s": "usc",
        "n": "Statistics MS",
        "en": "Master of Science in Statistics",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "1.5-2 years",
        "ddl": "Feb 1 (Fall only)",
        "lang": "TOEFL 100 / IELTS 7.0 / PTE 68",
        "test": "GRE not required",
        "tui": "待补",
        "url": "details/usc-stats-ms.html"
    },
    {
        "id": "ucla-ece-ms",
        "s": "ucla",
        "n": "Electrical and Computer Engineering MS",
        "en": "Master of Science in Electrical and Computer Engineering",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "2 years",
        "ddl": "Dec 15 (Fall)",
        "lang": "TOEFL 87 / IELTS 7.0",
        "test": "GRE not required (2027-2028 cycle)",
        "tui": "待补",
        "url": "details/ucla-ece-ms.html"
    },
    {
        "id": "notre-msee",
        "s": "notre",
        "n": "Electrical Engineering MSEE",
        "en": "Master of Science in Electrical Engineering",
        "deg": "MSEE",
        "lvl": "m",
        "stem": 1,
        "dur": "1-1.5 years",
        "ddl": "Dec 15 (Fall)",
        "lang": "TOEFL / IELTS / Duolingo",
        "test": "GRE recommended but not required",
        "tui": "待补",
        "url": "details/notre-msee.html"
    },
    {
        "id": "usc-spds-ms",
        "s": "usc",
        "n": "Spatial Data Science MS",
        "en": "Master of Science in Spatial Data Science",
        "deg": "MS",
        "lvl": "m",
        "stem": 1,
        "dur": "2 years (4 semesters)",
        "ddl": "待补",
        "lang": "TOEFL / IELTS (USC graduate standard)",
        "test": "GRE not required",
        "tui": "待补",
        "url": "details/usc-spds-ms.html"
    },
    {
        "id": "ut-mmi",
        "s": "ut",
        "n": "Management of Innovation MMI",
        "en": "Master of Management of Innovation",
        "deg": "MMI",
        "lvl": "m",
        "stem": 0,
        "dur": "12 months (8 months coursework + 4 months internship)",
        "ddl": "Feb 28 (Sep start)",
        "lang": "TOEFL 580 paper / 92 iBT (SGS standard)",
        "test": "GMAT/GRE optional",
        "tui": "待补",
        "url": "details/ut-mmi.html"
    },
]

# ---------- Detail page templates ----------
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 == "usc-stats-ms":
        return "The MS in Statistics at USC Dornsife Department of Mathematics provides rigorous training in statistical theory and methodology. Designed for students seeking careers in data analysis, pharmaceuticals, finance, insurance, market research, and government, the program combines mathematical foundations with applied statistical practice. Students may choose between a thesis option and a non-thesis option (via graduate probability exam)."
    if pid == "ucla-ece-ms":
        return "The MS in Electrical and Computer Engineering at UCLA Samueli School of Engineering offers both thesis and capstone (non-thesis) plans. The program is flexible, allowing students to tailor courses across established tracks (circuits, communications, signal processing, systems, solid-state, photonics, etc.) or design ad hoc tracks. Students work closely with faculty advisors and must complete requirements within two academic years."
    if pid == "notre-msee":
        return "The MSEE at University of Notre Dame Department of Electrical Engineering prepares students for advanced industrial or academic careers. Research areas include electronic circuits and systems, electronic materials and devices, communications, signal and image processing, high-speed circuits, microwave and millimeter-wave components, and solid-state devices. Both thesis and non-thesis options are available; typical completion is 1 to 1.5 years for full-time students."
    if pid == "usc-spds-ms":
        return "The MS in Spatial Data Science is a cross-disciplinary joint degree between USC Viterbi School of Engineering and Dornsife College Spatial Sciences Institute. It integrates data science engineering with spatial analysis and GIS. The curriculum is designed to be accessible to students from diverse backgrounds, including geography/GIS students without programming experience and CS/engineering students without geography background."
    if pid == "ut-mmi":
        return "The Master of Management of Innovation (MMI) at University of Toronto Mississauga (UTM) Institute for Management & Innovation is an accelerated 12-month professional degree designed for science, engineering, and IT graduates seeking management careers in technology-focused organizations. The program combines core business coursework (economics, strategy, finance, marketing, accounting, technology management) with a mandatory 4-month summer internship. Small class sizes (max 35) ensure interactive learning."
    return ""

def requirements_text(pid):
    if pid == "usc-stats-ms":
        return """<ul>
<li>Total: 30 units (excluding optional thesis)</li>
<li>Required courses: 9 units (MATH 541a, MATH 541b, MATH 550)</li>
<li>One course from each option A/B/C: 9 units total</li>
<li>Electives: at least 12 units from approved list (CS, DSO, Economics, ECE, Finance, ISE, Preventive Medicine, Psychology, etc.)</li>
<li>At least 20 of 30 units must be at 500-level or higher</li>
<li>All courses taken for letter grade; required courses must be B or higher</li>
<li>Two completion paths: <b>thesis</b> (MATH 594a/b) or <b>non-thesis</b> (pass graduate Probability exam)</li>
</ul>"""
    if pid == "ucla-ece-ms":
        return """<ul>
<li><b>Capstone Plan (non-thesis):</b> 8 formal graduate courses (5 ECE + 3 electives) + ECE 297 seminar + ECE 299 comprehensive exam</li>
<li><b>Thesis Plan:</b> 7 formal graduate courses (4 ECE + 3 electives) + ECE 297 seminar + 2 ECE 598 thesis units</li>
<li>All requirements must be completed within 2 academic years</li>
<li>Minimum cumulative GPA 3.0 each quarter</li>
<li>Electives may be chosen from BioE, ChemE, CEE, CS, ECE, MS&E, Math, MAE, Physics, Statistics</li>
<li>Major and minor sequences must be from different tracks (or approved ad hoc tracks)</li>
</ul>"""
    if pid == "notre-msee":
        return """<ul>
<li>Total: 30 semester credit hours</li>
<li><b>Non-thesis MSEE:</b> 30 credits with minimum 27 lecture credits; pass M.S. comprehensive exam</li>
<li><b>Thesis MSEE:</b> 30 credits with minimum 18 lecture credits + 6 thesis direction credits (EE 68599); submit and defend written thesis</li>
<li>Up to 9 credits may be taken from other departments</li>
<li>Up to 6 credits of advanced undergraduate (400-497 level) may count</li>
<li>Typical full-time completion: 3-4 regular academic semesters</li>
</ul>"""
    if pid == "usc-spds-ms":
        return """<ul>
<li>Total: 32 units</li>
<li>Required courses (6 courses / 24 units):
  <ul>
  <li>Foundation: DSCI 549 (Computational Thinking & DS) + SSCI 581 (Concepts for Spatial Thinking)</li>
  <li>Spatial core: SSCI 575 (Spatial Data Science) + SSCI 586 (GIS Programming & Customization)</li>
  <li>Data Science core: DSCI 510 (Programming for DS) + DSCI 550 (Data Science at Scale)</li>
  </ul>
</li>
<li>Electives: 8 units (4 spatial elective + 4 DS elective) from approved list</li>
<li>No prior programming or CS background required; introductory courses provided</li>
<li>Students with CS/engineering background may request waiver of introductory DS courses</li>
</ul>"""
    if pid == "ut-mmi":
        return """<ul>
<li>Total: 6.0 Full-Course Equivalents (FCEs)</li>
<li>4.5 FCEs required core courses (9 courses)</li>
<li>1.5 FCEs electives (3 courses, chosen across UofT disciplines)</li>
<li>0.5 FCE mandatory summer internship (May-August, 4 months)</li>
<li>Minimum 1 year / maximum 3 years to complete</li>
<li>September start only</li>
</ul>"""
    return ""

def curriculum_text(pid):
    if pid == "usc-stats-ms":
        return """<ul>
<li>MATH 541a / 541b - Introduction to Mathematical Statistics</li>
<li>MATH 550 - Statistical Consulting and Data Analysis</li>
<li>Option A (Probability): MATH 505a Applied Probability or MATH 507a Theory of Probability</li>
<li>Option B (Design/Time Series): MATH 542 ANOVA and Design or MATH 545 Introduction to Time Series</li>
<li>Option C (Numerical/Data): MATH 501 Numerical Analysis, MATH 502a, or PM 511aL Data Analysis</li>
<li>Elective areas: CS, Data Science, Economics, ECE, Finance, ISE, Mathematics, Preventive Medicine, Psychology, Public Planning, Sociology</li>
</ul>"""
    if pid == "ucla-ece-ms":
        return """<ul>
<li>Established tracks include: Circuits & Embedded Systems, Communications & Networking, Control & Signal Processing, Electrophysics, Integrated Circuits, Machine Learning, Photonics, Power & Energy, Solid-State & Semiconductors</li>
<li>ECE 297 - Graduate Seminar series</li>
<li>ECE 299 - Individual Study (comprehensive exam, capstone plan)</li>
<li>ECE 598 - Research (thesis plan)</li>
<li>Elective departments: BioE, ChemE, CEE, CS, MS&E, Math, MAE, Physics, Statistics</li>
</ul>"""
    if pid == "notre-msee":
        return """<ul>
<li>Research areas: systems theory, electromagnetics, digital signal & image processing, communication systems, high-speed circuits, microwave/mm-wave components, solid-state materials & devices</li>
<li>EE 68599 - Thesis Direction (6 credits for thesis option)</li>
<li>Cross-departmental electives allowed (up to 9 credits)</li>
<li>Advanced undergraduate (400-497) courses allowed up to 6 credits</li>
</ul>"""
    if pid == "usc-spds-ms":
        return """<ul>
<li>SSCI 575 - Spatial Data Science</li>
<li>SSCI 586 - GIS Programming and Customization</li>
<li>DSCI 510 - Principles of Programming for Data Science</li>
<li>DSCI 550 - Data Science at Scale</li>
<li>Spatial electives: SSCI 582 Spatial Databases, SSCI 583 Spatial Analysis & Modeling, SSCI 591 Web & Mobile GIS</li>
<li>DS electives: DSCI 551 Data Management, DSCI 552 Machine Learning, DSCI 553 Data Mining, DSCI 554 Visualization, DSCI 560 Practicum, DSCI 565 Deep Learning</li>
</ul>"""
    if pid == "ut-mmi":
        return """<ul>
<li><b>Fall:</b> MMI1010H Prices & Markets, MMI1020H Intro to Big Data Analysis, MMI1030H Marketing Science, MMI1040H Accounting, MMI1060H Finance + 1 elective</li>
<li><b>Winter:</b> MMI1050H Negotiations, MMI1070H Economics of Business Strategy, MMI1080H Management of Technology, MMI1090H Technology, Strategy & Policy + 2 electives</li>
<li><b>Summer:</b> MMI1100 Internship (4 months, mandatory)</li>
<li>Electives may be chosen from graduate courses across all UofT disciplines</li>
</ul>"""
    return ""

def admissions_text(pid):
    if pid == "usc-stats-ms":
        return """<ul>
<li>Bachelor's degree with strong math background: 3 semesters calculus (including multivariable), 1 semester linear algebra, 1 undergraduate probability, 1 undergraduate statistics</li>
<li>Minimum GPA 3.0; recent successful applicants typically 3.7+ (admission distribution, not minimum threshold)</li>
<li>TOEFL 100 / IELTS 7.0 / PTE 68</li>
<li>GRE not required</li>
<li>Application materials: transcripts, SOP, CV, 2-3 recommendation letters</li>
<li>Fall admission only; deadline February 1</li>
<li>No departmental funding for master's students; most students self-funded</li>
</ul>"""
    if pid == "ucla-ece-ms":
        return """<ul>
<li>B.S. degree in engineering or related field</li>
<li>Minimum cumulative GPA 3.0; most competitive applicants 3.5+ (admission distribution, not minimum threshold)</li>
<li>TOEFL 87 / IELTS 7.0</li>
<li>GRE not required for 2027-2028 admissions cycle</li>
<li>Application materials: transcripts, SOP, CV, 3 letters of recommendation</li>
<li>Official scores due by December 15</li>
</ul>"""
    if pid == "notre-msee":
        return """<ul>
<li>Undergraduate degree in engineering or physical sciences</li>
<li>GRE recommended but not required</li>
<li>TOEFL / IELTS / Duolingo (non-native English speakers)</li>
<li>Application materials: CV, statement of intent, 3 letters of recommendation, transcripts</li>
<li>Deadline: December 15 (Fall admission)</li>
<li>No departmental financial support for MSEE students; typically self-funded</li>
</ul>"""
    if pid == "usc-spds-ms":
        return """<ul>
<li>Bachelor's degree in STEM or related social science</li>
<li>Programming experience or at least one year of calculus recommended</li>
<li>Minimum GPA 3.0</li>
<li>TOEFL / IELTS (USC graduate standard for international students)</li>
<li>GRE not required</li>
<li>Application materials: transcripts, personal statement, CV, 2 letters of recommendation (highly recommended)</li>
<li>Joint admission review by both Viterbi and Dornsife</li>
</ul>"""
    if pid == "ut-mmi":
        return """<ul>
<li>4-year undergraduate degree in Science, Health/Life Sciences, Engineering, IT/CS, or other technical/science field</li>
<li>One undergraduate calculus or statistics course required</li>
<li>Minimum GPA 3.3 (B+ average) in last two years of study</li>
<li>Math and writing skills test as part of admission interview screening</li>
<li>Work experience not required</li>
<li>TOEFL / IELTS required if undergraduate degree not from English-instruction North American university</li>
<li>Application deadline: February 28; documents by March 15</li>
<li>Application fee: $125 CAD</li>
<li>Two academic letters of reference; one-page application letter; resume/CV</li>
<li>Small class size: maximum 35 students per cohort</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 using bracket-depth matching
# PROGRAMS is defined as const PROGRAMS=[ ... ];
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
# i now points just after the closing ]
insert_pos = i - 1  # position of ]
# Insert before the closing ]
# Check if previous char before ] is comma or not
prev_char = html[insert_pos - 1].strip()
if prev_char == ",":
    # already ends with comma, just append
    html = html[:insert_pos] + "\n" + new_block + html[insert_pos:]
else:
    # need to add comma
    html = html[:insert_pos] + ",\n" + new_block + html[insert_pos:]

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

# ---------- Append VD ----------
# Find VERIFIED_DETAILS=new Set([ ... ]);
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
# i now points just after the closing )
# We need to find the ] before the )
# Scan backwards from i-1 to find ]
close_paren = i - 1
# Find ] position
j = close_paren - 1
while j >= 0 and html[j] != "]":
    j -= 1
# j is position of ]
# Insert before ]
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)}")
