# -*- coding: utf-8 -*-
import json, io, sys, re, os
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
os.chdir(r"D:\work buddy\2026-11-05-14-15-52")

sname = {"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":"滑铁卢"}

snap = json.load(open("_daily_snapshot.json", encoding="utf-8"))
old = snap.get("programs", {})
cur = json.load(open("_daily_cur_tmp.json", encoding="utf-8"))

new_ids = [k for k in cur if k not in old]
print("新增条数:", len(new_ids))
print()

# 按学校分组
by_school = {}
for k in new_ids:
    s = cur[k]["s"]
    by_school.setdefault(s, []).append(k)

def pick_official(det_path):
    """从详情页 HTML 提取最像学校官网的 URL"""
    try:
        html = open(det_path, encoding="utf-8").read()
    except Exception:
        return ""
    urls = re.findall(r'https?://[^"\'<> )]+', html)
    # 排除 CDN / fonts / 本地
    bad = ("file://","googleapis","gstatic","cdn","jsdelivr","unpkg","cloudflare","github.io","fonts.")
    cands = []
    for u in urls:
        if any(b in u.lower() for b in bad):
            continue
        # 优先学校主域
        cands.append(u)
    if not cands:
        return ""
    # 选第一个看起来像招生/项目页的
    for u in cands:
        if any(k in u for k in ("admission","program","graduate","catalog","bulletin","sgs.","e-catalogue","college")):
            return u
    return cands[0]

lines = []
for s in sorted(by_school.keys(), key=lambda x: list(sname.keys()).index(x) if x in sname else 99):
    sn = sname.get(s, s)
    items = by_school[s]
    lines.append(f"\n【{sn}】{len(items)}条")
    for k in items:
        p = cur[k]
        det = p["url"]
        local = f"file:///D:/work%20buddy/2026-11-05-14-15-52/{det}"
        off = pick_official(det)
        line = f"- {sn} | {p['n']} | {p['deg']} | [详情页]({local})"
        if off:
            line += f" | [官网]({off})"
        lines.append(line)

out = "\n".join(lines)
open("_daily_report_lines.txt", "w", encoding="utf-8").write(out)
print(out[:3000])
print("...")
print("总行数:", len(lines))
