import re

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

new_records = [
    ('berkeley-meng-eecs', 'berkeley', '电子工程与计算机工程工程硕士（1 年 · MEng）', 'Master of Engineering in Electrical Engineering and Computer Sciences', 'MEng', 'm', 1, '9 months (Fall + Spring)',
     'Jan 6, 2027', 'TOEFL iBT 90 / IELTS 7.0', 'GRE optional; tech GPA 3.5/4.0, B- min',
     '~$27,788/semester non-resident', 'details/berkeley-meng-eecs.html'),
    ('berkeley-meng-ieor', 'berkeley', '工业工程与运筹学工程硕士（1 年 · MEng）', 'Master of Engineering in Industrial Engineering and Operations Research', 'MEng', 'm', 1, '9 months (Fall + Spring)',
     'Dec 15 (fall)', 'TOEFL iBT 90 / IELTS 7.0', 'GRE required (UC 3.5+ GPA waiver)',
     '~$27,788/semester non-resident', 'details/berkeley-meng-ieor.html'),
    ('mcg-ma-econ-thesis', 'mcg', '经济学文学硕士（论文型 · Thesis）', 'Master of Arts in Economics (Thesis)', 'MA', 'm', 0, '1.5-2 years',
     'Jan 15 (fall)', 'TOEFL iBT 100 / IELTS 7.0', 'GRE required (Canadian econ degree exempt); CGPA 3.0/4.0',
     '~CAD 20,000-25,000/year international', 'details/mcg-ma-econ-thesis.html'),
    ('princeton-meng-mae', 'princeton', '机械与航空航天工程工程硕士（10 个月 · MEng）', 'Master of Engineering in Mechanical and Aerospace Engineering', 'MEng', 'm', 1, '10 months (coursework-only)',
     'Dec 15 (fall)', 'TOEFL iBT 100 / IELTS 7.0', 'GRE not accepted; GPA 3.0/4.0',
     '~$60,000/year (self-funded)', 'details/princeton-meng-mae.html'),
    ('mit-mst', 'mit', '交通科学硕士（跨学科 · MST）', 'Master of Science in Transportation', 'MST', 'm', 1, '2 years (research thesis)',
     'Dec 15 (fall)', 'TOEFL iBT 100 / IELTS 7.0 / Duolingo 120+', 'GRE required (code 3514)',
     '~$60,000/year (RA/TA/fellowship)', 'details/mit-mst.html'),
]

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 ===
m = re.search(r'const PROGRAMS\s*=\s*\[', h)
if not m:
    raise SystemExit('PROGRAMS start not found')
start = m.end()
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
end_bracket = i - 1
new_h = h[:end_bracket] + new_block + '\n' + h[end_bracket:]

# === 2. Append new urls to VD 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')
paren_start = m2.end()
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
paren_end = j - 1

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]
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)})')
