import re

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

new_records = [
    ('harvard-edm', 'harvard', '教育学硕士（1 年 · EdM · Residential）', 'Master of Education (Ed.M.) Residential', 'EdM', 'm', 0, '1 academic year (Fall + Spring)',
     'Jan 5, 2026', 'TOEFL iBT / IELTS Academic / Duolingo', 'GRE optional; bachelor degree direct entry, no work exp required',
     '~$60,000+/year tuition', 'details/harvard-edm.html'),
    ('ucla-mlis', 'ucla', '图书馆与信息科学硕士（2 年 · MLIS · ALA 认证）', 'Master of Library and Information Science', 'MLIS', 'm', 0, '6 quarters (2 years)',
     'Dec 1, 2026', 'TOEFL iBT 100 / IELTS 7.0', 'GRE not required; min GPA 3.0; stats + programming prerequisites',
     '~$32,000/quarter non-resident', 'details/ucla-mlis.html'),
    ('uva-msds', 'uva', '数据科学硕士（11-15 个月 · MSDS · Residential）', 'Master of Science in Data Science (Residential)', 'MSDS', 'm', 1, '11-15 months (3-4 terms)',
     'Jan 15 (fall priority)', 'TOEFL iBT 90 / IELTS 7.0', 'GRE not required; Calc II/Linear Algebra/Programming/Statistics prerequisites',
     '~$60,000/year', 'details/uva-msds.html'),
    ('ubc-msc-stat-thesis', 'ubc', '统计学理学硕士（论文型 · MSc Thesis）', 'Master of Science in Statistics (Thesis)', 'MSc', 'm', 1, '2 years (30 credits)',
     'Dec 15 (fall priority)', 'TOEFL iBT 90 / IELTS 6.5', 'GRE not required; min avg 75%; faculty supervisor for thesis option',
     '~CAD 10,000-15,000/year (supervisor funding/TA)', 'details/ubc-msc-stat-thesis.html'),
    ('ubc-masc-ece', 'ubc', '电气与计算机工程应用科学硕士（论文型 · MASc）', 'Master of Applied Science in Electrical and Computer Engineering', 'MASc', 'm', 1, '24 months (30 credits)',
     'Jan 15, 2027 (fall)', 'TOEFL iBT 92 / IELTS 6.5', 'GRE not required; min GPA B+ (76-79%); ECE/BASc background',
     '~CAD 10,000-15,000/year (supervisor funding/TA)', 'details/ubc-masc-ece.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)})')
