"""扫描 PROGRAMS 中字段缺失的半核验页，按热门学校优先级排序"""
import re, json
from collections import Counter

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

# 提取 PROGRAMS 段
m = re.search(r'const PROGRAMS=(\[[\s\S]*?\]);', html)
if not m:
    print("PROGRAMS 未找到"); exit()
prog_str = m.group(1)

# 按 {id:"..."} 切块
entries = re.findall(r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|,?\n\];)', prog_str)
print(f"总条目: {len(entries)}")

# 热门学校优先级（CS/EE/金融/经济/BA/DS/统计）
hot_schools = ['cmu', 'gatech', 'illinois', 'umd', 'umich', 'gatech', 'usc', 'nyu', 'columbia', 'up', 'cornell', 'stanford', 'berkeley', 'ucla', 'mit', 'princeton', 'uchicago']

# 半核验：ddl/tui/test.cls 含"待补"或为空
half = []
for pid, body in entries:
    s_m = re.search(r's:"([^"]*)"', body)
    n_m = re.search(r'n:"([^"]*)"', body)
    deg_m = re.search(r'deg:"([^"]*)"', body)
    ddl_m = re.search(r'ddl:"([^"]*)"', body)
    tui_m = re.search(r'tui:"([^"]*)"', body)
    url_m = re.search(r'url:"([^"]*)"', body)
    test_m = re.search(r'test:\{cls:"([^"]*)"', body)
    s = s_m.group(1) if s_m else ''
    n = n_m.group(1) if n_m else ''
    deg = deg_m.group(1) if deg_m else ''
    ddl = ddl_m.group(1) if ddl_m else ''
    tui = tui_m.group(1) if tui_m else ''
    url = url_m.group(1) if url_m else ''
    test = test_m.group(1) if test_m else ''
    
    # 标记缺失字段
    missing = []
    if not ddl or '待补' in ddl: missing.append('ddl')
    if not tui or '待补' in tui: missing.append('tui')
    if not test or '待补' in test or '?' in test: missing.append('test')
    
    if missing:
        half.append({
            'id': pid, 's': s, 'n': n, 'deg': deg,
            'ddl': ddl, 'tui': tui, 'test': test, 'url': url,
            'missing': missing
        })

print(f"半核验页（缺字段）: {len(half)}")

# 按学校优先级 + 缺字段数排序
def score(item):
    s = 0
    if item['s'] in hot_schools:
        s -= hot_schools.index(item['s']) + 1
    s -= len(item['missing']) * 10  # 缺越多越优先
    return s

half.sort(key=score)

# 输出前 20 条候选
print("\n=== 候选前 20 ===")
for i, h in enumerate(half[:20]):
    print(f"{i+1}. [{h['s']}] {h['id']} | {h['n']} | {h['deg']} | 缺: {h['missing']} | url={h['url']}")

# 保存候选
with open('_r316_half_candidates.json', 'w', encoding='utf-8') as f:
    json.dump(half[:50], f, ensure_ascii=False, indent=2)
print(f"\n前 50 条候选已存 _r316_half_candidates.json")
