import re

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

new_programs = [
    {
        'id': 'upenn-math-ma',
        's': 'up',
        'n': '数学文学硕士',
        'en': 'Master of Arts in Mathematics',
        'dept': '数学系',
        'college': '文理学院 SAS',
        'disc': 'stat',
        'lvl': 'm',
        'deg': 'AM',
        'dur': '在校全日制',
        'stem': 1,
        'rank': '藤校数学硕士',
        'test': {'cls': 'GRE Not Required（可提交）'},
        'ddl': '2027-02-15',
        'lang': 'TOEFL 100+（口语20+）',
        'tui': '待补',
        'url': 'details/upenn-math-ma.html',
    },
    {
        'id': 'usc-abe-ms',
        's': 'usc',
        'n': '应用生物统计与流行病学硕士',
        'en': 'MS in Applied Biostatistics and Epidemiology',
        'dept': '人口与公共卫生科学系',
        'college': 'Keck 医学院',
        'disc': 'stat',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '在校全日制',
        'stem': 1,
        'rank': '生统+流行病',
        'test': {'cls': 'GRE Not Required'},
        'ddl': '2026-12-01（优先）',
        'lang': 'TOEFL/IELTS',
        'tui': '待补',
        'url': 'details/usc-applied-biostatistics-epidemiology-ms.html',
    },
    {
        'id': 'usc-spatial-ds',
        's': 'usc',
        'n': '空间数据科学硕士',
        'en': 'MS in Spatial Data Science',
        'dept': '计算机系 / 空间科学研究所',
        'college': 'Viterbi 工程学院 / Dornsife 文理学院',
        'disc': 'ds',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '在校全日制',
        'stem': 1,
        'rank': '空间数据科学交叉',
        'test': {'cls': 'GRE Not Required'},
        'ddl': '待补',
        'lang': 'TOEFL/IELTS',
        'tui': '待补',
        'url': 'details/usc-spatial-data-science-ms.html',
    },
    {
        'id': 'usc-mmi-ms',
        's': 'usc',
        'n': '分子微生物学与免疫学硕士',
        'en': 'MS in Molecular Microbiology and Immunology',
        'dept': '分子微生物与免疫系',
        'college': 'Keck 医学院',
        'disc': 'bio',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '在校全日制',
        'stem': 1,
        'rank': '生物医学研究',
        'test': {'cls': 'GRE Not Required / MCAT 可选'},
        'ddl': '待补',
        'lang': 'TOEFL/IELTS',
        'tui': '待补',
        'url': 'details/usc-molecular-microbiology-immunology-ms.html',
    },
    {
        'id': 'usc-cgb-ms',
        's': 'usc',
        'n': '癌症基因组学与生物信息学硕士',
        'en': 'MS in Cancer Genomics and Bioinformatics',
        'dept': '癌症生物系',
        'college': 'Keck 医学院',
        'disc': 'bio',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '在校全日制',
        'stem': 1,
        'rank': '癌症基因组+生物信息',
        'test': {'cls': '待补'},
        'ddl': '待补',
        'lang': '待补',
        'tui': '待补',
        'url': 'details/usc-cancer-genomics-bioinformatics-ms.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 追加完成 ===')
