import json
import re

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

# 读取 index_main.html 中已入库的 PROGRAMS
with open('index_main.html','r',encoding='utf-8') as f:
    html = f.read()

# 提取 PROGRAMS 中已有的 det 路径
existing_dets = set(re.findall(r'\{id:"[^"]+"[^}]*?url:"(details/[^"]+)"', html))
print(f'已入库 PROGRAMS 数: {len(existing_dets)}')

# 跳过的学校（403 不可达）
skip_schools = {'berkeley'}

# 已排除的边界项
skip_dets = {
    'details/geo-cybersecurity-risk-management-ms.html',  # SCS 继续教育+在线
}

# 优先级
priority = ['cs','ee','fin','econ','ba','ds','stat','mech','bio','mgmt']

def is_master(item):
    det = item.get('det','')
    # 排除 PhD
    if 'phd' in det.lower() or 'doctor' in det.lower():
        return False
    # 排除 online/在职
    en = item.get('en','').lower()
    if 'online' in en or 'part-time' in en or 'professional' in en:
        return False
    return True

# 筛选
candidates = []
for item in todo:
    det = item.get('det','')
    s = item.get('s','')
    
    # 跳过已入库
    if det in existing_dets:
        continue
    # 跳过不可达学校
    if s in skip_schools:
        continue
    # 跳过边界项
    if det in skip_dets:
        continue
    # 只要硕士
    if not is_master(item):
        continue
    
    candidates.append(item)

print(f'筛选后候选硕士数: {len(candidates)}')
print()

# 按优先级排序
def sort_key(item):
    disc = item.get('disc','zzz')
    try:
        idx = priority.index(disc)
    except:
        idx = 99
    return (idx, item.get('s',''), item.get('en',''))

sorted_candidates = sorted(candidates, key=sort_key)

print('前 20 条候选硕士:')
for i, item in enumerate(sorted_candidates[:20]):
    disc = item.get('disc','?')
    s = item.get('s','?')
    n = item.get('n','?')
    en = item.get('en','?')[:70]
    det = item.get('det','?')[:60]
    print(f'{i+1}. [{disc}] {s} - {n}')
    print(f'   en: {en}')
    print(f'   det: {det}')
    print()
