import re

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

new_records = [
    ('berkeley-meng-bioe', 'berkeley', '生物工程工程硕士（1 年 · MEng）', 'Master of Engineering in Bioengineering', 'MEng', 'm', 1, '9 months (Fall + Spring)',
     'Jan 6, 2027', 'TOEFL iBT 90 / IELTS 7.0', 'GRE not required; min GPA 3.0/4.0, admit avg 3.63',
     '~$27,788/semester non-resident', 'details/berkeley-meng-bioe.html'),
    ('berkeley-meng-cee', 'berkeley', '土木与环境工程工程硕士（1 年 · MEng）', 'Master of Engineering in Civil and Environmental Engineering', 'MEng', 'm', 1, '9 months (Fall + Spring)',
     'Early Jan, 2027', 'TOEFL iBT 90 / IELTS 7.0', 'GRE not required; min GPA 3.0/4.0; BS engineering',
     '~$27,788/semester non-resident', 'details/berkeley-meng-cee.html'),
    ('princeton-mse-cee', 'princeton', '土木与环境工程工程硕士（MSE，论文型）', 'Master of Science in Engineering in Civil and Environmental Engineering', 'MSE', 'm', 1, '2 years (research thesis)',
     'Dec 15 (fall)', 'TOEFL iBT 100 / IELTS 7.0', 'GRE optional; min GPA 3.0/4.0; faculty adviser required',
     '~$60,000/year (RA/TA/fellowship varies)', 'details/princeton-mse-cee.html'),
    ('princeton-meng-cbe', 'princeton', '化学与生物工程工程硕士（10 个月 · MEng）', 'Master of Engineering in Chemical and Biological Engineering', 'MEng', 'm', 1, '10 months (coursework-only)',
     'Dec 15 (fall)', 'TOEFL iBT 100 / IELTS 7.0', 'GRE not accepted; GPA B (3.0) average',
     '~$60,000/year (self-funded)', 'details/princeton-meng-cbe.html'),
    ('ubc-masc-me', 'ubc', '机械工程应用科学硕士（论文型 · MASc）', 'Master of Applied Science in Mechanical Engineering', 'MASc', 'm', 1, '24 months (research thesis)',
     'Dec 15 (fall, priority)', 'TOEFL iBT 90 / IELTS 6.5', 'GRE not required; min avg 76-79%; faculty supervisor required',
     '~CAD 10,000-15,000/year (supervisor funding/TA)', 'details/ubc-masc-me.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)})')
