#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""从 Acalog / Modern Campus 课程目录站采集研究生项目：项目名、学位、学院、官方主页。

用法：python harvest.py <school_id> <list_url> <link_prefix>
输出：out_<school_id>.json
"""
import re, sys, json, ssl, time
import urllib.request, urllib.error
from concurrent.futures import ThreadPoolExecutor

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
HDRS = {"User-Agent": UA, "Accept": "text/html,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.9"}
CTX = ssl.create_default_context()
CTX.check_hostname = False
CTX.verify_mode = ssl.CERT_NONE

# 硕士层级学位（终端的专业硕士/授课型硕士）
MASTER_DEG = {
    "MS", "M.S.", "MEng", "M.Eng.", "MPS", "MA", "M.A.", "MBA", "MPA", "MPP",
    "MFA", "MPH", "MRP", "MMH", "MEM", "MSE", "MLS", "MArch", "MLA", "MUP",
    "MEd", "MSW", "MHA", "MIS", "MAcc", "MFin", "MSC", "MMus", "MDes", "MIB",
    "MST", "MPhil", "MPA-URP", "MSc", "MAS", "MEngg", "MPS-RE", "MIS-IT",
}
# 明显不属于硕士的
SKIP_DEG = {"BA", "BS", "B.S.", "BArch", "BFA", "Minor", "PhD", "Ph.D.", "JD",
            "MD", "DVM", "EdD", "DNS", "DMA", "Certificate", "Cert"}


def get(url, timeout=30):
    req = urllib.request.Request(url, headers=HDRS)
    with urllib.request.urlopen(req, timeout=timeout, context=CTX) as r:
        return r.getcode(), r.read()


def text(h):
    h = re.sub(r"(?is)<(script|style)[^>]*>.*?</\1>", " ", h)
    h = re.sub(r"(?s)<[^>]+>", "\n", h)
    h = h.replace("&nbsp;", " ").replace("&amp;", "&").replace("&#8217;", "'")
    return "\n".join(l.strip() for l in h.split("\n") if l.strip())


def parse_list(html, prefix):
    """返回 [(name, deg, url)]"""
    rows = []
    seen = set()
    for m in re.finditer(r'<a\b[^>]*href="([^"]+)"[^>]*>(.*?)</a>', html, re.S | re.I):
        href, raw = m.group(1), m.group(2)
        if prefix not in href:
            continue
        name = re.sub(r"<[^>]+>", " ", raw)
        name = re.sub(r"&nbsp;|&amp;", " ", name)
        name = re.sub(r"\s+", " ", name).strip()
        if not name or len(name) > 120:
            continue
        # 提取括号或逗号后的学位标记
        mm = re.search(r"[\(\,]\s*([A-Za-z\.\-]{2,12})\s*\)?\s*$", name)
        deg = mm.group(1) if mm else ""
        base = re.sub(r"[\(\,]\s*[A-Za-z\.\-]{2,12}\s*\)?\s*$", "", name).strip()
        if href in seen:
            continue
        seen.add(href)
        rows.append((base, deg, href))
    return rows


COLLEGE_STOP = re.compile(r"^(Print Options|Program Website|Taxonomy Codes|CIP:|HEGIS:|NYSED:|Program Description|2026-2027|20\d\d-20\d\d Edition)")


def parse_detail(html):
    """返回 (college, website, desc)"""
    college = ""
    website = ""
    m = re.search(r'<a[^>]*href="([^"]+)"[^>]*>\s*Program Website\s*</a>', html, re.I)
    if m:
        website = m.group(1)
    t = text(html)
    lines = [l for l in t.split("\n") if l]
    # 主内容区标题之后、Taxonomy Codes 之前的那一行即学院名
    idx = None
    for i, l in enumerate(lines):
        if l.startswith("Taxonomy Codes"):
            idx = i
            break
    if idx:
        for j in range(idx - 1, max(-1, idx - 8), -1):
            l = lines[j]
            if re.search(r"(College|School|Faculty|Institute|Division) of |^College of |^School of ", l) and len(l) < 90:
                college = l
                break
        if not college and idx >= 1:
            cand = lines[idx - 1]
            if len(cand) < 90 and not COLLEGE_STOP.match(cand):
                college = cand
    # Program Description 之后的第一段
    desc = ""
    for i, l in enumerate(lines):
        if l.startswith("Program Description"):
            for j in range(i + 1, min(i + 6, len(lines))):
                if len(lines[j]) > 60:
                    desc = lines[j]
                    break
            break
    return college, website, desc


def main():
    sid, list_url, prefix = sys.argv[1], sys.argv[2], sys.argv[3]
    code, raw = get(list_url)
    html = raw.decode("utf-8", "ignore")
    rows = parse_list(html, prefix)
    cand = []
    for base, deg, href in rows:
        d = deg.strip()
        if d in SKIP_DEG:
            continue
        if d in MASTER_DEG or re.match(r"^(MS|MA|MEng|MPS|MBA|MPA|MFA|MPH)\b", d):
            if href.startswith("/"):
                href = re.sub(r"^(https?://[^/]+).*", r"\1", list_url) + href
            elif not href.startswith("http"):
                continue
            cand.append({"en": base, "deg": d, "url": href})
    print(f"list rows={len(rows)}  master candidates={len(cand)}")

    def work(p):
        try:
            c, r = get(p["url"], timeout=25)
            p["college"], p["site"], p["desc"] = parse_detail(r.decode("utf-8", "ignore"))
        except Exception as e:
            p["college"], p["site"], p["desc"] = "", "", ""
            p["err"] = type(e).__name__
        return p

    with ThreadPoolExecutor(max_workers=10) as ex:
        out = list(ex.map(work, cand))
    json.dump(out, open(f"out_{sid}.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    got = sum(1 for p in out if p["college"])
    print(f"college ok={got}/{len(out)}  -> out_{sid}.json")
    for p in out[:8]:
        print(f'  {p["deg"]:<5} {p["en"][:45]:<47} {p["college"][:40]}')


if __name__ == "__main__":
    main()
