import re

with open('index_main.html','r',encoding='utf-8') as f:
    html = f.read()

new_programs = [
    {
        'id': 'cornell-bme-ms',
        's': 'cornell',
        'n': '生物医学工程硕士（研究型）',
        'en': 'Master of Science in Biomedical Engineering',
        'dept': 'Meinig School of Biomedical Engineering',
        'college': 'Duffield College of Engineering',
        'disc': 'bio',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '研究型论文硕士， typically 2年',
        'stem': 1,
        'rank': '藤校生物医学工程研究型硕士',
        'test': {'cls': 'GRE Not required or accepted'},
        'ddl': '2026-12-01（秋季入学）',
        'lang': 'TOEFL/IELTS（Grad School 统一标准）',
        'tui': '自费，具体费率待补',
        'url': 'details/cornell-bme-ms.html',
    },
    {
        'id': 'cornell-bee-ms',
        's': 'cornell',
        'n': '生物与环境工程硕士（研究型）',
        'en': 'Master of Science in Biological and Environmental Engineering',
        'dept': 'Biological and Environmental Engineering',
        'college': 'CALS 农业与生命科学学院',
        'disc': 'bio',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '研究型论文硕士， typically 2年',
        'stem': 1,
        'rank': 'CALS 跨学科工程研究型硕士',
        'test': {'cls': 'GRE Not required'},
        'ddl': '2026-12-01（秋季）；2026-10-01（春季）',
        'lang': 'TOEFL/IELTS（Grad School 统一标准）',
        'tui': '自费/奖学金混合，具体费率待补',
        'url': 'details/cornell-bee-ms.html',
    },
    {
        'id': 'rice-meml-oncampus',
        's': 'rice',
        'n': '工程管理与领导力硕士（在校全日制）',
        'en': 'Master of Engineering Management and Leadership (On-Campus)',
        'dept': 'Rice Center for Engineering Leadership',
        'college': 'George R. Brown School of Engineering',
        'disc': 'mgmt',
        'lvl': 'm',
        'deg': 'MEML',
        'dur': '职业型非论文，10门课30-32学分',
        'stem': 0,
        'rank': '工程+管理跨学科硕士',
        'test': {'cls': 'GRE 推荐但不要求'},
        'ddl': '滚动录取，建议尽早提交',
        'lang': 'TOEFL/IELTS（英语授课学位可豁免）',
        'tui': '具体费率待补',
        'url': 'details/rice-meml-oncampus.html',
    },
    {
        'id': 'usc-me-emgmt-dual-ms',
        's': 'usc',
        'n': '机械工程与工程管理双学位硕士',
        'en': 'Dual Degree MS Mechanical Engineering / MS Engineering Management',
        'dept': 'Aerospace & Mechanical Engineering / Industrial & Systems Engineering',
        'college': 'Viterbi School of Engineering',
        'disc': 'mech',
        'lvl': 'm',
        'deg': 'MS (Dual)',
        'dur': '1.5-2年，双学位整合',
        'stem': 1,
        'rank': '工程+管理双学位',
        'test': {'cls': '2027申请不要求 GRE'},
        'ddl': '2026-12-15（奖学金）；2027-01-15（最终）；春季 10/15',
        'lang': 'TOEFL/IELTS（Grad School 统一标准）',
        'tui': 'Viterbi 学分费率，总学分约38-42',
        'url': 'details/usc-me-emgmt-dual-ms.html',
    },
    {
        'id': 'uw-civil-engineering-meng-coop',
        's': 'uw',
        'n': '土木工程工程硕士（带薪实习 Co-op）',
        'en': 'Master of Engineering in Civil Engineering (Co-op)',
        'dept': 'Department of Civil and Environmental Engineering',
        'college': 'Faculty of Engineering',
        'disc': 'mech',
        'lvl': 'm',
        'deg': 'MEng',
        'dur': '16-20个月（4-5学期，含1个co-op学期）',
        'stem': 0,
        'rank': '加拿大 Co-op 带薪实习硕士',
        'test': {'cls': 'GRE 仅对加/美以外学位申请者要求'},
        'ddl': '9月入学 2/1；1月入学 6/1；5月入学 10/1',
        'lang': 'TOEFL iBT 80（写作22/口语20/阅读20/听力18）；IELTS 6.5',
        'tui': '国际生自费，具体费率待补',
        'url': 'details/uw-civil-engineering-meng-coop.html',
    },
]

def prog_to_js(p):
    return (
        '{id:"' + p['id'] + '",s:"' + p['s'] + '",n:"' + p['n'] + '",en:"' + p['en'] + '",'
        'dept:"' + p['dept'] + '",college:"' + p['college'] + '",disc:"' + p['disc'] + '",'
        'lvl:"' + p['lvl'] + '",deg:"' + p['deg'] + '",dur:"' + p['dur'] + '",'
        'stem:' + str(p['stem']) + ',rank:"' + p['rank'] + '",'
        'test:{cls:"' + p['test']['cls'] + '"},'
        'ddl:"' + p['ddl'] + '",lang:"' + p['lang'] + '",tui:"' + p['tui'] + '",'
        'url:"' + p['url'] + '"}'
    )

# 定位 PROGRAMS 数组结束位置（括号深度匹配）
prog_marker = 'const PROGRAMS=['
prog_start = html.find(prog_marker)
arr_start = html.find('[', prog_start)
depth = 0
i = arr_start
while i < len(html):
    if html[i] == '[':
        depth += 1
    elif html[i] == ']':
        depth -= 1
        if depth == 0:
            arr_end = i
            break
    i += 1

# 幂等检查
existing_urls = set(re.findall(r'url:"(details/[^"]+\.html)"', html))
new_entries = []
for p in new_programs:
    if p['url'] not in existing_urls:
        new_entries.append(p)
    else:
        print(f'跳过已存在: {p["url"]}')

if not new_entries:
    print('全部已存在，无需追加')
else:
    insert_str = ',' + ','.join([prog_to_js(p) for p in new_entries])
    html = html[:arr_end] + insert_str + html[arr_end:]
    print(f'已追加 {len(new_entries)} 条 PROGRAMS 记录')

# 定位 VERIFIED_DETAILS 集合结束位置（括号深度匹配）
vd_marker = 'const VERIFIED_DETAILS=new Set(['
vd_start = html.find(vd_marker)
vd_arr_start = html.find('[', vd_start)
depth = 0
i = vd_arr_start
while i < len(html):
    if html[i] == '[':
        depth += 1
    elif html[i] == ']':
        depth -= 1
        if depth == 0:
            vd_arr_end = i
            break
    i += 1

vd_content = html[vd_arr_start:vd_arr_end+1]
new_vd = []
for p in new_programs:
    if p['url'] not in vd_content:
        new_vd.append(p['url'])
    else:
        print(f'VD 已存在: {p["url"]}')

if new_vd:
    insert_vd = ',' + ','.join(['"' + u + '"' for u in new_vd])
    html = html[:vd_arr_end] + insert_vd + html[vd_arr_end:]
    print(f'已登记 {len(new_vd)} 条 VD')

with open('index_main.html', 'w', encoding='utf-8') as f:
    f.write(html)

print(f'\n文件大小: {len(html)} 字符')
print('=== PROGRAMS + VD 追加完成 ===')
