# -*- coding: utf-8 -*-
import io, sys, json, re, ssl, urllib.request, os
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")

html = open("index_main.html", encoding="utf-8").read()
vd = re.search(r"const VERIFIED_DETAILS=new Set\(\[(.*?)\]\);", html, re.S).group(1)
vd_set = set(re.findall(r'"(details/[^"]+)"', vd))
print("VD 总数:", len(vd_set))

# 已入库 Cornell PROGRAMS
prog_ids = re.findall(r'\{id:"(cornell-[^"]+)"', html)
print("已入库 Cornell PROGRAMS:", len(prog_ids))
for x in prog_ids:
    print("   ", x)

cands = ["cornell-c60e314", "cornell-cffc740", "cornell-ca5b01c",
         "cornell-cdfe6e6", "cornell-ce9af91"]
for c in cands:
    det = "details/" + c + ".html"
    in_vd = det in vd_set
    in_prog = ('id:"' + c + '"' in html)
    row = re.search(r'\[[^\]]*"'+c+r'[^]]*\]', html)
    print(f"{c}: VD={in_vd} PROG={'id-in' if in_prog else 'no'} det_exists={os.path.exists(det)}")
    if row:
        print("   CATD:", row.group(0)[:240])

# todo 中 Cornell 条目
todo = json.load(open("todo_upgrade.json", encoding="utf-8"))
if isinstance(todo, dict):
    todo = todo.get("items") or todo.get("todo") or list(todo.values())[0]
cornell_todo = [t for t in todo if str(t.get("s","")) == "cornell"]
print("\ntodo Cornell 条数:", len(cornell_todo))
for t in cornell_todo[:25]:
    print("   ", t.get("en"), "|", t.get("deg"), "|", t.get("det"))

# 官网可达性
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
urls = {
    "CEE MEng": "https://www.duffield.cornell.edu/cee/meng/",
    "Systems MEng": "https://www.duffield.cornell.edu/sys/meng/",
    "EngPhys MEng": "https://www.duffield.cornell.edu/aep/meng/",
    "EAS MEng": "https://www.duffield.cornell.edu/eas/meng/",
    "BEE CALS": "https://cals.cornell.edu/biological-environmental-engineering",
}
for name, u in urls.items():
    try:
        req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"})
        b = urllib.request.urlopen(req, context=ctx, timeout=20).read()
        print(f"[{name}] {u} -> {len(b)} bytes")
    except Exception as e:
        print(f"[{name}] {u} -> ERR {type(e).__name__}: {e}")
