import re

h = open('index_main.html', encoding='utf-8').read()

# 5 new records to append to PROGRAMS
new_records = [
    # id, s, n, en, deg, lvl, stem, dur, ddl, lang, test_cls, tui, url
    ('yale-mpp', 'yale', '全球事务公共政策硕士', 'Master of Public Policy in Global Affairs', 'MPP', 'm', 0, '2 years (4 semesters)',
     'Dec (fall)', 'TOEFL iBT 100 / IELTS 7.0', 'GRE not required (holistic review); work/volunteer/internship strongly preferred',
     'Tuition fully covered via Jackson fellowship', 'details/yale-mpp.html'),
    ('brown-mph-inperson', 'brown', '公共卫生硕士（in-person · Providence）', 'Master of Public Health (In-Person)', 'MPH', 'm', 1, '2 years full-time on-campus',
     'Dec 1 (fall)', 'TOEFL iBT 100 / IELTS 7.0', 'GRE optional; bachelor degree',
     '~$60,000/year', 'details/brown-mph-inperson.html'),
    ('uiuc-ms-me', 'illinois', '机械工程理学硕士（thesis option）', 'MS in Mechanical Engineering', 'MS', 'm', 1, '1.5-2 years',
     'Fall 12/15; Spring 9/15', 'TOEFL iBT 103 (Speaking 24) / IELTS 7.0', 'GRE required; min GPA 3.0/4.0',
     '~$33,000/year (out-of-state; TA/RA funded)', 'details/uiuc-ms-me.html'),
    ('berkeley-meng-me', 'berkeley', '机械工程工程硕士（1 年 · MEng）', 'Master of Engineering in Mechanical Engineering', 'MEng', 'm', 1, '9 months (Fall + Spring)',
     'Dec 15 (fall)', 'TOEFL iBT 90 / IELTS 7.0', 'GRE optional (avg admit Quant >90% / Verbal >70% / Analytic >3.5, 录取分布非最低门槛)',
     '~$27,788/semester non-resident', 'details/berkeley-meng-me.html'),
    ('ubc-mph', 'ubc', '公共卫生硕士（MPH · Vancouver）', 'Master of Public Health', 'MPH', 'm', 0, '20 months (5 terms)',
     '12/15/2026 for Sept 2027', 'TOEFL iBT 100 / IELTS 7.0', 'GRE not required; bachelor degree + public health related experience preferred',
     '~CAD 27,000-30,000/year international', 'details/ubc-mph.html'),
]

# Build record JS strings
def fmt(rec):
    pid, s, n, en, deg, lvl, stem, dur, ddl, lang, test, tui, url = rec
    return (f'{{id:"{pid}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test}"}},tui:"{tui}",url:"{url}"}}')

new_block = ',\n' + ',\n'.join(fmt(r) for r in new_records)

# === 1. Append to PROGRAMS array ===
# Find const PROGRAMS = [ ... ];
m = re.search(r'const PROGRAMS\s*=\s*\[', h)
if not m:
    raise SystemExit('PROGRAMS start not found')
start = m.end()  # position right after '['
# Walk bracket depth to find matching ']'
depth = 1
i = start
in_str = False
str_ch = ''
while i < len(h) and depth > 0:
    c = h[i]
    if in_str:
        if c == '\\':
            i += 2
            continue
        if c == str_ch:
            in_str = False
    else:
        if c in ('"', "'"):
            in_str = True
            str_ch = c
        elif c == '[':
            depth += 1
        elif c == ']':
            depth -= 1
    i += 1
# i now points just after the closing ']'
end_bracket = i - 1  # position of ']'
# Insert new_block right before ']'
# Check char before ']' — should be ',' or '}'
before = h[end_bracket-1]
if before == '[':
    # empty array
    new_h = h[:end_bracket] + '\n' + ',\n'.join(fmt(r) for r in new_records) + '\n' + h[end_bracket:]
else:
    new_h = h[:end_bracket] + new_block + '\n' + h[end_bracket:]

# === 2. Append new urls to VD Set ===
# Find const VERIFIED_DETAILS=new Set([ ... ]);
m2 = re.search(r'VERIFIED_DETAILS\s*=\s*new\s*Set\s*\(', new_h)
if not m2:
    raise SystemExit('VD Set start not found')
# The Set( argument starts at m2.end(); find matching ')' with paren depth
# But inside the paren there's an array [...], which we need to close first
paren_start = m2.end()  # position right after '('
depth = 1
j = paren_start
in_str = False
str_ch = ''
while j < len(new_h) and depth > 0:
    c = new_h[j]
    if in_str:
        if c == '\\':
            j += 2
            continue
        if c == str_ch:
            in_str = False
    else:
        if c in ('"', "'"):
            in_str = True
            str_ch = c
        elif c == '(':
            depth += 1
        elif c == ')':
            depth -= 1
    j += 1
# j now points just after matching ')'
paren_end = j - 1  # position of ')'

# Within the paren, we have the array literal. We need to insert new urls before the closing ']' of the array.
# Easier: extract all "details/..." strings inside, then rebuild array. But to be safe, find the array's closing ']' before paren_end.
# Walk backward from paren_end to find the last ']' that closes the array.
# Simpler: forward scan from paren_start to find ']' that closes outer array.
arr_depth = 0
k = paren_start
in_str = False
str_ch = ''
arr_close = -1
while k < paren_end:
    c = new_h[k]
    if in_str:
        if c == '\\':
            k += 2
            continue
        if c == str_ch:
            in_str = False
    else:
        if c in ('"', "'"):
            in_str = True
            str_ch = c
        elif c == '[':
            arr_depth += 1
        elif c == ']':
            arr_depth -= 1
            if arr_depth == 0:
                arr_close = k
                break
    k += 1
if arr_close < 0:
    raise SystemExit('VD array close not found')

new_urls = [r[12] for r in new_records]
# Check last non-whitespace char before arr_close
# Find the comma situation
# Look backwards from arr_close
p = arr_close - 1
while p >= paren_start and new_h[p] in ' \t\n\r':
    p -= 1
last_ch = new_h[p] if p >= paren_start else ''
if last_ch == ',':
    # already comma-terminated
    vd_insert = ',\n  "' + '",\n  "'.join(new_urls) + '"\n'
else:
    vd_insert = ',\n  "' + '",\n  "'.join(new_urls) + '"\n'

new_h = new_h[:arr_close] + vd_insert + new_h[arr_close:]

open('index_main.html', 'w', encoding='utf-8').write(new_h)
print(f'[OK] PROGRAMS +{len(new_records)}, VD +{len(new_urls)}')
print(f'File size: {len(new_h)} chars (was {len(h)})')
