#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""批次 13：并入康奈尔大学（88 个硕士项目，13 个学院），并刷新覆盖率文案。"""
import re, collections

P = "index_main.html"
h = open(P, encoding="utf-8").read()

rows = open("rows_cornell.txt", encoding="utf-8").read()
rows = "\n".join(l for l in rows.splitlines() if l.strip())

# 1) 插入 CATD
mark = '["umich", "公共卫生学院", "Nutritional Sciences", "营养科学（系）", "MPH/MS/PhD", "https://sph.umich.edu/ns/index.html", "med"],\n];'
assert mark in h, "CATD 结尾标记未命中"
h = h.replace(mark, '["umich", "公共卫生学院", "Nutritional Sciences", "营养科学（系）", "MPH/MS/PhD", "https://sph.umich.edu/ns/index.html", "med"],\n' + rows + '\n];', 1)

# 2) SCHOOLS 增加康奈尔
sm = ' {id:"uw",cn:"滑铁卢大学",en:"University of Waterloo",country:"CA",qs:"QS 官方：并列第 113"}\n];'
assert sm in h, "SCHOOLS 结尾标记未命中"
h = h.replace(sm, ' {id:"uw",cn:"滑铁卢大学",en:"University of Waterloo",country:"CA",qs:"QS 官方：并列第 113"},\n'
              ' {id:"cornell",cn:"康奈尔大学",en:"Cornell University",country:"US",qs:""}\n];', 1)

# 3) 重算覆盖统计并刷新文案
a = h.find("const CATD=[")
b = h.find("const DOCDEG")
seg = h[a:b]
recs = re.findall(r'\["([a-z0-9\-]+)", "([^"]*)", "([^"]*)", "([^"]*)", "([^"]*)", "([^"]*)", "([^"]*)"\]', seg)
by_school = collections.Counter(r[0] for r in recs)
by_college = {(r[0], r[1]) for r in recs}
h = re.sub(r'目录层已录入 <b>\d+ 所院校 · \d+ 个学院／学系 · \d+ 条</b>',
           f'目录层已录入 <b>{len(by_school)} 所院校 · {len(by_college)} 个学院／学系 · {len(recs)} 条</b>', h, count=1)

open(P, "w", encoding="utf-8").write(h)
print("写入完成")
print("院校数:", len(by_school), "学院数:", len(by_college), "条目:", len(recs))
print(dict(by_school))
