import re

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

# 新增的 5 条 PROGRAMS 记录
new_programs = [
    {
        'id': 'emory-cs-ms',
        's': 'emory',
        'n': '计算机科学硕士',
        'en': 'M.S. in Computer Science',
        'dept': '计算机科学系',
        'college': 'Laney Graduate School',
        'disc': 'cs',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '1.5-2年',
        'stem': 1,
        'rank': 'Top30',
        'test': {'cls': 'GRE 建议提交，不强制'},
        'ddl': '3月1日（仅秋季）',
        'lang': 'TOEFL 90+',
        'tui': '待补',
        'url': 'details/emory-computer-science-ms.html'
    },
    {
        'id': 'emory-ds-ms',
        's': 'emory',
        'n': '数据科学硕士',
        'en': 'Master of Science in Data Science',
        'dept': '数据与决策科学系',
        'college': 'Laney Graduate School',
        'disc': 'ds',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '12个月',
        'stem': 1,
        'rank': 'Top30',
        'test': {'cls': 'GRE 要求'},
        'ddl': '1月15日（优先）/ 4月15日（最终）',
        'lang': 'TOEFL 100 / IELTS 7.0',
        'tui': '待补',
        'url': 'details/emory-data-science-datascims-ms.html'
    },
    {
        'id': 'notre-acms-ms',
        's': 'notre',
        'n': '应用计算数学与统计学硕士（专业型）',
        'en': 'MS in Applied and Computational Mathematics and Statistics (Professional)',
        'dept': '应用计算数学与统计系',
        'college': 'College of Science',
        'disc': 'stat',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '1-2年',
        'stem': 1,
        'rank': 'Top20',
        'test': {'cls': 'GRE 可选但强烈建议'},
        'ddl': '待补',
        'lang': 'TOEFL 100（口语23）',
        'tui': '待补',
        'url': 'details/notre-applied-and-computational-mathematics-and-statistics-ms.html'
    },
    {
        'id': 'harvard-stats-am',
        's': 'harvard',
        'n': '统计学文学硕士（Terminal AM）',
        'en': 'Master of Arts in Statistics (Terminal AM)',
        'dept': '统计系',
        'college': 'GSAS',
        'disc': 'stat',
        'lvl': 'm',
        'deg': 'AM',
        'dur': '1-2年',
        'stem': 1,
        'rank': 'Top10',
        'test': {'cls': 'GRE General 要求'},
        'ddl': '12月1日',
        'lang': '待补',
        'tui': '待补',
        'url': 'details/harvard-statistics.html'
    },
    {
        'id': 'princeton-cs-mse',
        's': 'princeton',
        'n': '计算机科学工程硕士',
        'en': 'M.S.E. in Computer Science',
        'dept': '计算机科学系',
        'college': '工程学院',
        'disc': 'cs',
        'lvl': 'm',
        'deg': 'MSE',
        'dur': '2年',
        'stem': 1,
        'rank': 'Top10',
        'test': {'cls': 'GRE General 不接受'},
        'ddl': '12月1日（仅秋季）',
        'lang': 'TOEFL 口语28 / IELTS 口语8',
        'tui': '待补',
        'url': 'details/princeton-computer-science.html'
    }
]

# 检查是否已存在（幂等）
for p in new_programs:
    if f'id:"{p["id"]}"' in html:
        print(f'跳过已存在: {p["id"]}')
        new_programs.remove(p)

if not new_programs:
    print('所有 5 条均已存在，无需追加')
    exit(0)

# 定位 PROGRAMS 数组结束位置
# PROGRAMS 定义方式: const PROGRAMS=[
# 用括号深度匹配
prog_start = html.find('const PROGRAMS=[')
if prog_start == -1:
    print('错误：找不到 PROGRAMS 定义')
    exit(1)

# 从 [ 开始，深度匹配找到结束的 ]
bracket_start = html.find('[', prog_start)
depth = 0
i = bracket_start
while i < len(html):
    if html[i] == '[':
        depth += 1
    elif html[i] == ']':
        depth -= 1
        if depth == 0:
            prog_end = i
            break
    i += 1

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

# 构造新记录的 JS 字符串
def format_program(p):
    test_str = f'{{cls:"{p["test"]["cls"]}"}}'
    return (
        f'{{id:"{p["id"]}",s:"{p["s"]}",n:"{p["n"]}",en:"{p["en"]}",'
        f'dept:"{p["dept"]}",college:"{p["college"]}",disc:"{p["disc"]}",'
        f'lvl:"{p["lvl"]}",deg:"{p["deg"]}",dur:"{p["dur"]}",stem:{p["stem"]},'
        f'rank:"{p["rank"]}",test:{test_str},'
        f'ddl:"{p["ddl"]}",lang:"{p["lang"]}",tui:"{p["tui"]}",url:"{p["url"]}"}}'
    )

new_records = ',\n' + ',\n'.join([format_program(p) for p in new_programs])

# 在 ] 前插入新记录
new_html = html[:prog_end] + new_records + '\n' + html[prog_end:]

# 现在处理 VERIFIED_DETAILS
vd_start = new_html.find('const VERIFIED_DETAILS = new Set([')
if vd_start == -1:
    print('错误：找不到 VERIFIED_DETAILS 定义')
    exit(1)

# 找到 Set 结束位置
paren_start = new_html.find('([', vd_start)
depth = 0
i = paren_start
while i < len(new_html):
    if new_html[i] == '(':
        depth += 1
    elif new_html[i] == ')':
        depth -= 1
        if depth == 0:
            vd_end = i
            break
    i += 1

print(f'VERIFIED_DETAILS Set 结束位置: {vd_end}')

# 检查哪些 det 路径还没在 VD 中
new_vd_items = []
for p in new_programs:
    if f'"{p["url"]}"' not in new_html[vd_start:vd_end]:
        new_vd_items.append(p['url'])

if new_vd_items:
    vd_insert = ',\n  ' + ',\n  '.join([f'"{u}"' for u in new_vd_items])
    # 在 ) 前插入
    new_html = new_html[:vd_end] + vd_insert + '\n' + new_html[vd_end:]
    print(f'追加 VD 条目: {len(new_vd_items)} 条')
else:
    print('VD 条目均已存在')

# 写回文件
with open('index_main.html','w',encoding='utf-8') as f:
    f.write(new_html)

print(f'完成：追加 {len(new_programs)} 条 PROGRAMS 记录')
