import re

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

# 检查哪些 id 已存在
existing_ids = re.findall(r'id:"([^"]+)"', html)
print(f'当前 PROGRAMS id 总数: {len(existing_ids)}')

# 本轮准备追加的 5 条（其中 2 条可能已存在）
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'
    }
]

# 过滤掉已存在的
to_add = [p for p in new_programs if p['id'] not in existing_ids]
print(f'需追加: {len(to_add)} 条')
for p in to_add:
    print(f'  - {p["id"]}')

if not to_add:
    print('全部已存在，无需追加')
    exit(0)

# 定位 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}')

# 构造新记录
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 to_add])

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

# 处理 VERIFIED_DETAILS（注意：无空格格式 const VERIFIED_DETAILS=new Set([）
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 中
vd_section = new_html[vd_start:vd_end]
new_vd_items = []
for p in to_add:
    if f'"{p["url"]}"' not in vd_section:
        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)} 条')
    for u in new_vd_items:
        print(f'  - {u}')
else:
    print('VD 条目均已存在')

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

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