import re

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

new_records = [
    ('caltech-msee', 'caltech', '电子工程理学硕士（MSEE · 1 年 · terminal MS · 自费）', 'Master of Science in Electrical Engineering (MSEE)', 'MSEE', 'm', 1, '1 academic year (3 terms) / 135 units',
     '申请窗口 11/15 - 12/15，Fall 入学', 'TOEFL / IELTS / PTE / Duolingo（无最低分，要求 strong English）', 'GRE encouraged；3 推荐信；不招已有 US master\'s 学位者；自费为主',
     'USD 71,022/年 (2026-27)', 'details/caltech-msee.html'),
    ('caltech-ms-aero', 'caltech', '航空理学硕士（GALCIT · 1 年 · 无 thesis · terminal MS）', 'Master of Science in Aeronautics (GALCIT)', 'MS', 'm', 1, '1 year / 135 units / 5 core courses',
     '申请窗口 11/15 - 12/15，Fall 入学', 'TOEFL / IELTS / PTE / Duolingo（无最低分）', 'GRE optional；3 推荐信；优先给计划读 PhD 的学生',
     'USD 71,022/年 (2026-27)', 'details/caltech-ms-aero.html'),
    ('uchicago-harris-mpp', 'uchicago', '公共政策硕士（MPP · 2 年 · flagship · Harris 学院）', 'Master of Public Policy (MPP, Harris School of Public Policy)', 'MPP', 'm', 0, '2 years (6 quarters)',
     'Autumn Quarter 入学（精确轮次待补）', 'TOEFL iBT / IELTS Academic（具体分数待补）', 'GRE required 或满足 4 项 waiver 条件之一；300 词 Motivation Statement；可选 500 词 Short Essay',
     '约 USD 70,000+/年（精确待补）', 'details/uchicago-harris-mpp.html'),
    ('uchicago-mscapp', 'uchicago', '计算分析与公共政策理学硕士（MSCAPP · 2 年 · Harris × CS 联合 · STEM）', 'Master of Science in Computational Analysis and Public Policy (MSCAPP)', 'MSCAPP', 'm', 1, '2 years (6 quarters)',
     'Autumn Quarter 入学（精确轮次待补）', 'TOEFL iBT / IELTS Academic（具体分数待补）', 'GRE required 或 waiver；11 门 core courses（统计+CS+ML+微观+Program Evaluation）；Year 1 summer internship',
     '约 USD 70,000+/年（精确待补）', 'details/uchicago-mscapp.html'),
    ('vandy-ms-cs', 'vanderbilt', '计算机科学理学硕士（MSCS · 在校 · research-oriented · 可匹配导师）', 'Master of Science in Computer Science (MSCS, on-campus)', 'MS', 'm', 1, '1.5-2 years typical',
     'Fall priority Jan 15, 2027 / regular Mar 1, 2027; Spring Oct 15', 'TOEFL iBT ~90 / IELTS 7.0 (no band <6.0) / Duolingo 130', 'GRE indefinitely waived；申请时填感兴趣 topics and faculty 匹配 adviser；WES 认证',
     '约 USD 60,000+/年（精确待补）', 'details/vandy-ms-cs.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)

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:]

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