import json, re, sys
sys.stdout.reconfigure(encoding='utf-8')

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

# 提取已入库的 en 字段
existing_en = set()
for m in re.finditer(r'\{id:"[^"]+"(.*?)\}(?=\{id:"|\n\];)', html):
    block = m.group(0)
    en_m = re.search(r'en:"([^"]*)"', block)
    if en_m:
        existing_en.add(en_m.group(1).strip().lower())

# 只要硕士（deg 里含 MS/MA/MEng/MPS/MPH/MSS/MSE/MFA 等，不含 PhD）
master_only = []
for item in todo:
    deg = item.get('deg','').strip()
    if 'phd' in deg.lower() or 'doctor' in deg.lower():
        continue
    en = item.get('en','').strip().lower()
    found = False
    for e in existing_en:
        if en and (en == e or en in e or e in en) and len(en) > 5:
            found = True
            break
    if not found:
        master_only.append(item)

# 按学校分组
from collections import defaultdict
by_school = defaultdict(list)
for item in master_only:
    by_school[item['s']].append(item)

print('=== 各学校待核验硕士项目数 ===')
for s in sorted(by_school.keys(), key=lambda x: -len(by_school[x])):
    print(f"{s}: {len(by_school[s])}")

print()
print('=== 按热门学科筛选（cs/ee/fin/econ/ba/ds/stats/mech/bio/mgmt）===')
hot_disc = ['cs','ee','fin','econ','ba','ds','stats','mech','me','bio','mgmt','math','data','engineering','business','publichealth','computerscience']
hot = []
for item in master_only:
    disc = item.get('disc','').lower()
    if any(d in disc for d in hot_disc):
        hot.append(item)

print(f'hot master candidates: {len(hot)}')
print()
# 按学校分组打印
by_school_hot = defaultdict(list)
for item in hot:
    by_school_hot[item['s']].append(item)
for s in sorted(by_school_hot.keys()):
    print(f'--- {s} ({len(by_school_hot[s])}) ---')
    for item in by_school_hot[s][:5]:
        print(f"  {item['en']} | {item['deg']} | disc={item.get('disc','')}")
