import re

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

# 5条新 PROGRAMS 记录
new_programs = [
    {
        'id': 'princeton-mfin',
        's': 'princeton',
        'n': '金融学硕士',
        'en': 'Master in Finance (M.Fin.)',
        'dept': 'Bendheim 金融中心',
        'college': '研究生院',
        'disc': 'fin',
        'lvl': 'm',
        'deg': 'MFin',
        'dur': '2年在校全日制',
        'stem': 1,
        'rank': 'Top3 金融硕士',
        'test': {'cls': 'GRE/GMAT 接受但不要求'},
        'ddl': '2026-12-15',
        'lang': 'TOEFL/DET/IELTS',
        'tui': '待补',
        'url': 'details/princeton-finance.html',
    },
    {
        'id': 'ucsd-mqf',
        's': 'ucsd',
        'n': '量化金融硕士',
        'en': 'Master of Quantitative Finance (MQF)',
        'dept': 'Rady 商学院',
        'college': 'Rady School of Management',
        'disc': 'fin',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '1年在校全日制',
        'stem': 1,
        'rank': 'STEM 量化金融',
        'test': {'cls': 'GMAT/GRE Required'},
        'ddl': '待补',
        'lang': '待补',
        'tui': '待补',
        'url': 'details/ucsd-quantitative-finance-ms.html',
    },
    {
        'id': 'emory-econ-ms',
        's': 'emory',
        'n': '经济学理学硕士',
        'en': 'Master of Science in Economics',
        'dept': '经济系',
        'college': 'Laney 研究生院',
        'disc': 'econ',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '在校全日制',
        'stem': 0,
        'rank': 'Emory 经济学硕士',
        'test': {'cls': 'GRE Optional（2027秋）'},
        'ddl': '2027-01-15（优先）',
        'lang': 'TOEFL/IELTS/DET',
        'tui': '待补',
        'url': 'details/emory-economics-ms.html',
    },
    {
        'id': 'usc-ms-aee',
        's': 'usc',
        'n': '应用经济学与计量经济学',
        'en': 'MS in Applied Economics and Econometrics (MS AEE)',
        'dept': '经济系',
        'college': 'Dornsife 文理学院',
        'disc': 'econ',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '在校全日制',
        'stem': 1,
        'rank': 'STEM 应用经济',
        'test': {'cls': '待补'},
        'ddl': '待补',
        'lang': '待补',
        'tui': '待补',
        'url': 'details/usc-c6e2c49.html',
    },
    {
        'id': 'cornell-mps-aem',
        's': 'cornell',
        'n': '应用经济学与管理专业研究硕士',
        'en': 'Master of Professional Studies in Applied Economics and Management',
        'dept': 'Dyson 应用经济与管理学院',
        'college': 'SC Johnson 商学院',
        'disc': 'mgmt',
        'lvl': 'm',
        'deg': 'MPS',
        'dur': '10个月在校全日制',
        'stem': 1,
        'rank': '藤校 STEM 1年制',
        'test': {'cls': 'GMAT/GRE 可申请豁免'},
        'ddl': '待补',
        'lang': '待补',
        'tui': '$73,946',
        'url': 'details/cornell-cb05803.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)
if prog_start == -1:
    prog_marker = 'const PROGRAMS = ['
    prog_start = html.find(prog_marker)
print(f'PROGRAMS 起始位置: {prog_start}')

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

print(f'PROGRAMS 数组结束位置: {arr_end}')

# 幂等检查
existing_urls = 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)
if vd_start == -1:
    vd_marker = 'const VERIFIED_DETAILS = new Set(['
    vd_start = html.find(vd_marker)
print(f'\nVD 集合起始位置: {vd_start}')

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

print(f'VD 集合结束位置: {vd_arr_end}')

# 检查哪些 VD 还没登记
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 追加完成 ===')
