import re

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

new_records = [
    ('duke-mms-fob', 'duke', '管理研究硕士（MMS: Foundations of Business · 10 个月 · STEM · Fuqua）',
     'Master of Management Studies: Foundations of Business (MMS: FOB, Fuqua School of Business)',
     'MMS', 'm', 1, '10 months, full-time residential (July start, graduate May)',
     'R1 2026/10/7 / R2 2027/1/13；面试邀请 R1 11/9 / R2 2/5',
     'TOEFL iBT / IELTS Academic（具体分数待补）',
     'GRE/GMAT 接受（Middle 80% GRE V 151-168 / Q 152-170；GMAT Focus 525-695，录取分布非最低门槛）；可 waiver',
     '约 USD 75,000+/10-month（精确待补）',
     'details/duke-mms-fob.html'),
    ('yale-mam', 'yale', '资产管理硕士（Master\'s in Asset Management · 9 个月 · STEM · SOM）',
     "Master's in Asset Management (MAM, Yale School of Management)",
     'MAM', 'm', 1, '9 months, full-time in-residence (July start, graduate May)',
     'Fall 入学（7/31 前需获学士学位；具体轮次待补）',
     'TOEFL iBT / IELTS Academic（具体分数待补）',
     'GRE/GMAT 接受（录取分布非最低门槛）；strong quantitative background required',
     '约 USD 80,000+/9-month（精确待补）',
     'details/yale-mam.html'),
    ('emory-mfin', 'emory', '金融学硕士（MFin · 10/16 个月 · STEM · CFA 协会认证 · Goizueta）',
     'Master of Finance (MFin, Goizueta Business School)',
     'MFin', 'm', 1, '10 months (August start, graduate May) 或 16 months (含 summer internship)',
     'Fall（8 月）入学；具体轮次待补',
     'TOEFL iBT / IELTS Academic（具体分数待补）',
     'GRE/GMAT required（录取分布非最低门槛）；2 推荐信；Essays',
     '约 USD 70,000+/10-month（精确待补）',
     'details/emory-mfin.html'),
    ('uchicago-harris-macrm', 'uchicago', '公共政策硕士（研究方法证书方向）（MACRM · 2 年 · STEM · Harris）',
     'MA in Public Policy with Certificate in Research Methods (MACRM, Harris School of Public Policy)',
     'MA', 'm', 1, '2 years full-time (6 quarters, Autumn start)',
     'Autumn Quarter 入学；与 PhD 同批申请（通常 Dec/Jan 截止，具体轮次待补）',
     'TOEFL iBT / IELTS Academic（具体分数待补）',
     'GRE required 或满足 4 项 waiver 之一；3 推荐信；Research Statement 800 words；Writing Sample',
     '约 USD 75,000+/年（精确待补）',
     'details/uchicago-harris-macrm.html'),
    ('cornell-mps-mgmt', 'cornell', '管理学专业研究硕士（MPS in Management · 10 个月 · STEM · Johnson · Ithaca）',
     'Master of Professional Studies (MPS) in Management (Samuel Curtis Johnson Graduate School of Management)',
     'MPS', 'm', 1, '10 months, full-time residential (August start, graduate May) - 30 credit hours',
     'Fall（8 月）入学；具体轮次待补',
     'TOEFL iBT / IELTS Academic（具体分数待补）',
     'GRE/GMAT 政策待补（Holistic review）；面向 non-business 本科背景',
     '约 USD 70,000+/10-month（精确待补）',
     'details/cornell-mps-mgmt.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)})')
