import json
import re
from datetime import datetime

# 读取当前 index_main.html
with open('index_main.html','r',encoding='utf-8') as f:
    html = f.read()

# 提取 PROGRAMS 段
prog_start = html.find('const PROGRAMS=[')
if prog_start == -1:
    print('未找到 PROGRAMS')
    exit(1)

# 找 PROGRAMS 结束位置（括号深度匹配）
depth = 0
i = prog_start + len('const PROGRAMS=')
in_str = False
str_char = None
prog_end = -1

while i < len(html):
    c = html[i]
    if in_str:
        if c == '\\':
            i += 2
            continue
        if c == str_char:
            in_str = False
    else:
        if c in ('"', "'", '`'):
            in_str = True
            str_char = c
        elif c == '[':
            depth += 1
        elif c == ']':
            depth -= 1
            if depth == 0:
                prog_end = i
                break
    i += 1

prog_text = html[prog_start:prog_end]

# 用正则提取每条 {id,s,n,en,deg,url}
pattern = r'\{id:"([^"]+)"([\s\S]*?)(?=\{id:"|,?\n\];)'
matches = re.findall(pattern, prog_text)

current_programs = {}
for m in matches:
    pid = m[0]
    rest = m[1]
    # 提取 s, n, en, deg, url
    s_m = re.search(r's:"([^"]*)"', rest)
    n_m = re.search(r'n:"([^"]*)"', rest)
    en_m = re.search(r'en:"([^"]*)"', rest)
    deg_m = re.search(r'deg:"([^"]*)"', rest)
    url_m = re.search(r'url:"([^"]*)"', rest)
    current_programs[pid] = {
        's': s_m.group(1) if s_m else '',
        'n': n_m.group(1) if n_m else '',
        'en': en_m.group(1) if en_m else '',
        'deg': deg_m.group(1) if deg_m else '',
        'url': url_m.group(1) if url_m else '',
    }

print(f'当前 PROGRAMS 数: {len(current_programs)}')

# 读取昨天快照
with open('_daily_snapshot.json','r',encoding='utf-8') as f:
    old_snapshot = json.load(f)

old_programs = old_snapshot.get('programs', {})
print(f'昨天快照数: {len(old_programs)}')

# diff
new_ids = []
url_changed = []

for pid, info in current_programs.items():
    if pid not in old_programs:
        new_ids.append(pid)
    else:
        if old_programs[pid].get('url','') != info['url']:
            url_changed.append(pid)

print(f'\n新增 id: {len(new_ids)}')
for pid in new_ids:
    print(f'  + {pid}: {current_programs[pid]["n"]} | {current_programs[pid]["url"]}')

print(f'\nURL 变更 id: {len(url_changed)}')
for pid in url_changed:
    print(f'  ~ {pid}: {old_programs[pid]["url"]} -> {current_programs[pid]["url"]}')

# 学校名映射
school_map = {
    'col':'哥伦比亚','up':'宾大','cmu':'卡内基梅隆','usc':'南加州','nyu':'纽约',
    'umich':'密歇根安娜堡','jhu':'约翰霍普金斯','duke':'杜克','nu':'西北','cornell':'康奈尔',
    'illinois':'UIUC','uchicago':'芝加哥','mit':'麻省理工','princeton':'普林斯顿','harvard':'哈佛',
    'yale':'耶鲁','caltech':'加州理工','stanford':'斯坦福','dartmouth':'达特茅斯','brown':'布朗',
    'rice':'莱斯','vanderbilt':'范德堡','wustl':'圣路易斯华盛顿','notre':'圣母','emory':'埃默里',
    'geo':'乔治城','berkeley':'伯克利','ucla':'加州洛杉矶','uva':'弗吉尼亚','unc':'北卡教堂山',
    'gatech':'佐治亚理工','ucsd':'加州圣地亚哥','ut':'多伦多','ubc':'UBC','mcg':'麦吉尔','uw':'滑铁卢'
}

# 输出日报格式
print('\n' + '='*60)
print('📅 11月22日 09:30 项目库日报')
print('='*60)
print(f'(a) 当前总数：院校 36 校 / 核验 PROGRAMS {len(current_programs)} 条 / 目录 CATD 2817 / VD 696 / 死链 0')
print(f'(b) 昨天快照：{old_snapshot.get("snapshot_at","未知")}，共 {len(old_programs)} 条')

if not new_ids and not url_changed:
    print('\n(e) 过去 24 小时无新增/核验升级项目')
else:
    print('\n(d) 过去 24 小时变更明细：')
    for pid in new_ids:
        info = current_programs[pid]
        s_name = school_map.get(info['s'], info['s'])
        file_url = f'file:///D:/work%20buddy/2026-11-05-14-15-52/{info["url"]}'
        print(f'  【新增】{s_name} | {info["n"]} | {info["deg"]} | {file_url}')
    for pid in url_changed:
        info = current_programs[pid]
        s_name = school_map.get(info['s'], info['s'])
        file_url = f'file:///D:/work%20buddy/2026-11-05-14-15-52/{info["url"]}'
        print(f'  【变更】{s_name} | {info["n"]} | {info["deg"]} | {file_url}')

print('\n(f) 主页面检查链接：')
print('  file:///D:/work%20buddy/2026-11-05-14-15-52/index_main.html')
print('  （点击即可在浏览器打开检查）')

# 写回新快照
new_snapshot = {
    'snapshot_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    'count': len(current_programs),
    'programs': current_programs
}

with open('_daily_snapshot.json','w',encoding='utf-8') as f:
    json.dump(new_snapshot, f, ensure_ascii=False, indent=2)

print(f'\n(g) 新快照已写回：{len(current_programs)} 条')
