import re

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

new_records = [
    ('berkeley-meng-mse', 'berkeley', '材料科学与工程工程硕士（1 年 · MEng）', 'Master of Engineering in Materials Science and Engineering', 'MEng', 'm', 1, '9 months (Fall + Spring)',
     'Jan 14, 2027', 'TOEFL iBT 90 / IELTS 7.0', 'GRE not required; min GPA 3.0/4.0',
     '~$27,788/semester non-resident', 'details/berkeley-meng-mse.html'),
    ('berkeley-meng-ne', 'berkeley', '核工程工程硕士（1 年 · MEng）', 'Master of Engineering in Nuclear Engineering', 'MEng', 'm', 1, '9 months (Fall + Spring)',
     'Jan 6, 2027', 'TOEFL iBT 90 / IELTS 7.0', 'GRE not required; BS engineering required (not necessarily NE)',
     '~$27,788/semester non-resident', 'details/berkeley-meng-ne.html'),
    ('princeton-mse-cbe', 'princeton', '化学与生物工程工程硕士（MSE，论文型）', 'Master of Science in Engineering in Chemical and Biological Engineering', 'MSE', 'm', 1, '15-21 months (research thesis)',
     'Dec 15 (fall)', 'TOEFL iBT 100 / IELTS 7.0', 'GRE not accepted; GPA B (3.0) average',
     '~$60,000/year (RA/fellowship varies)', 'details/princeton-mse-cbe.html'),
    ('princeton-meng-cee', 'princeton', '土木与环境工程工程硕士（1 年 · MEng）', 'Master of Engineering in Civil and Environmental Engineering', 'MEng', 'm', 1, '1 academic year (coursework-only)',
     'Dec 15 (fall)', 'TOEFL iBT 100 / IELTS 7.0', 'GRE optional; GPA 3.0/4.0; engineering background',
     '~$60,000/year (self-funded)', 'details/princeton-meng-cee.html'),
    ('mcg-mist', 'mcg', '信息研究硕士（ALA 认证 · Project 方向）', 'Master of Information Studies (Project)', 'MIST', 'm', 0, '1.5-2 years (48 credits)',
     'Jan 15 (fall)', 'TOEFL iBT 100 / IELTS 7.0', 'GRE not required; min CGPA 3.0/4.0',
     '~CAD 10,000-15,000/year international', 'details/mcg-mist.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)})')
