import re

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

# 要追加的5个PROGRAMS记录
new_programs = [
    {
        'id': 'ucla-mqe-2027',
        's': 'ucla',
        'n': '量化经济学硕士',
        'en': 'Master of Quantitative Economics',
        'dept': '经济系',
        'college': '社会科学学院',
        'disc': 'econ',
        'lvl': 'm',
        'deg': 'MQE',
        'dur': '1.5-2年',
        'stem': 1,
        'rank': 'Top 30',
        'test': {'cls': 'GRE可选提交'},
        'ddl': '滚动录取：11/1 / 12/1 / 6/30',
        'lang': 'TOEFL/IELTS',
        'tui': '$1,288/学分×48学分',
        'url': 'details/ucla-master-of-quantitative-economics-ms.html'
    },
    {
        'id': 'uva-msds-res-2027',
        's': 'uva',
        'n': '数据科学硕士（在校全日制）',
        'en': 'M.S. in Data Science (Residential)',
        'dept': '数据科学学院',
        'college': '数据科学学院',
        'disc': 'ds',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '12-15个月',
        'stem': 1,
        'rank': 'Top 30',
        'test': {'cls': '详见官网'},
        'ddl': 'Priority 12/15 / Regular 3/1 / Rolling 6/15',
        'lang': 'TOEFL/IELTS',
        'tui': '详见官网',
        'url': 'details/uva-data-science-ms-ms.html'
    },
    {
        'id': 'rice-mstat-2027',
        's': 'rice',
        'n': '统计学硕士',
        'en': 'Master of Statistics',
        'dept': '统计系',
        'college': '工程学院',
        'disc': 'stat',
        'lvl': 'm',
        'deg': 'MStat',
        'dur': '1.5-2年',
        'stem': 1,
        'rank': 'Top 20',
        'test': {'cls': 'GRE建议提交，不强制'},
        'ddl': '国际生5/1 / 国内生7/1',
        'lang': 'TOEFL iBT优先',
        'tui': '详见官网',
        'url': 'details/rice-statistics.html'
    },
    {
        'id': 'ucsd-msds-hdsi-2027',
        's': 'ucsd',
        'n': '数据科学硕士（在校全日制）',
        'en': 'M.S. in Data Science',
        'dept': 'Halıcıoğlu数据科学研究所',
        'college': 'HDSI',
        'disc': 'ds',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '2年',
        'stem': 1,
        'rank': 'Top 30',
        'test': {'cls': 'GRE不要求'},
        'ddl': '暂定12/2',
        'lang': 'TOEFL/IELTS',
        'tui': '自支持型项目，详见官网',
        'url': 'details/ucsd-data-science-ms.html'
    },
    {
        'id': 'ucsd-ms-stat-2027',
        's': 'ucsd',
        'n': '统计学硕士',
        'en': 'M.S. in Statistics',
        'dept': '数学系',
        'college': '物理科学学院',
        'disc': 'stat',
        'lvl': 'm',
        'deg': 'MS',
        'dur': '2年',
        'stem': 1,
        'rank': 'Top 30',
        'test': {'cls': 'GRE General不要求，Math Subject强烈建议'},
        'ddl': '2/3',
        'lang': 'TOEFL/IELTS',
        'tui': '详见官网',
        'url': 'details/ucsd-statistics-ms.html'
    },
]

# 构造要插入的文本
def prog_to_str(p):
    return f'{{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:{p["stem"]},rank:"{p["rank"]}",test:{{cls:"{p["test"]["cls"]}"}},ddl:"{p["ddl"]}",lang:"{p["lang"]}",tui:"{p["tui"]}",url:"{p["url"]}"}}'

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

# 找到 PROGRAMS 数组的结束位置
# 用括号深度匹配
prog_start = html.find('const PROGRAMS=[')
if prog_start == -1:
    print('未找到 PROGRAMS 数组')
    exit(1)

# 从 PROGRAMS 开始位置往后找，匹配括号深度
depth = 0
i = prog_start + len('const PROGRAMS=')
in_str = False
str_char = None
prog_end = -1

while i < len(html):
    c = html[i]
    if in_str:
        if c == '\\':
            i += 2
            continue
        if c == str_char:
            in_str = False
    else:
        if c in ('"', "'", '`'):
            in_str = True
            str_char = c
        elif c == '[':
            depth += 1
        elif c == ']':
            depth -= 1
            if depth == 0:
                prog_end = i
                break
    i += 1

if prog_end == -1:
    print('未找到 PROGRAMS 数组结束位置')
    exit(1)

print(f'PROGRAMS 开始位置: {prog_start}')
print(f'PROGRAMS 结束位置: {prog_end}')

# 在结束位置前插入新记录
new_html = html[:prog_end] + new_prog_text + '\n' + html[prog_end:]

# 现在处理 VERIFIED_DETAILS 集合
vd_m = re.search(r'VERIFIED_DETAILS\s*=\s*new Set\(\[(.*?)\]\)', new_html, re.S)
if vd_m:
    vd_block = vd_m.group(1)
    new_vds = [p['url'] for p in new_programs]
    # 检查哪些不在里面
    to_add = []
    for v in new_vds:
        if f'"{v}"' not in vd_block:
            to_add.append(v)
    if to_add:
        insert_text = ',\n  "' + '",\n  "'.join(to_add) + '"'
        new_vd_block = vd_block.rstrip() + insert_text
        new_html = new_html.replace(vd_block, new_vd_block)
        print(f'VD 集合新增: {len(to_add)} 个')
    else:
        print('VD 集合无需新增')
else:
    print('未找到 VERIFIED_DETAILS 集合')

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

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