#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""批次 14：并入伊利诺伊大学厄巴纳-香槟分校（133 个硕士项目，14 个学院）。"""
import re, collections

P = "index_main.html"
h = open(P, encoding="utf-8").read()
rows = "\n".join(l for l in open("rows_illinois.txt", encoding="utf-8").read().splitlines() if l.strip())

# 1) CATD 末尾插入
m = re.search(r'(const CATD=\[.*?)(\n\];)', h, re.S)
assert m, "CATD 区块未定位"
tail = m.group(1)
h = h.replace(tail + m.group(2), tail + "\n" + rows + m.group(2), 1)

# 2) SCHOOLS 增加
sm = ' {id:"cornell",cn:"康奈尔大学",en:"Cornell University",country:"US",qs:""}\n];'
assert sm in h
h = h.replace(sm, ' {id:"cornell",cn:"康奈尔大学",en:"Cornell University",country:"US",qs:""},\n'
              ' {id:"illinois",cn:"伊利诺伊大学厄巴纳-香槟分校",en:"University of Illinois Urbana-Champaign",country:"US",qs:""}\n];', 1)

# 3) 统计文案
a = h.find("const CATD=[")
b = h.find("const DOCDEG")
recs = re.findall(r'\["([a-z0-9\-]+)", "([^"]*)", "([^"]*)", "([^"]*)", "([^"]*)", "([^"]*)", "([^"]*)"\]', h[a:b])
by_s = collections.Counter(r[0] for r in recs)
by_c = {(r[0], r[1]) for r in recs}
h = re.sub(r'目录层已录入 <b>\d+ 所院校 · \d+ 个学院／学系 · \d+ 条</b>',
           f'目录层已录入 <b>{len(by_s)} 所院校 · {len(by_c)} 个学院／学系 · {len(recs)} 条</b>', h, count=1)
old = '康奈尔 13 个学院 88 条。'
new = '康奈尔 13 个学院 88 条、伊利诺伊（UIUC）14 个学院 133 条。'
if old in h and new not in h:
    h = h.replace(old, new, 1)

open(P, "w", encoding="utf-8").write(h)
print("院校", len(by_s), "学院", len(by_c), "条目", len(recs))
print(dict(by_s))
