#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""基于 curl 的 Acalog 采集器（绕过 python 代理问题）。

用法：python harvest2.py <sid> <list_url> <link_prefix> [--college "固定学院名"]
"""
import re, sys, json, subprocess, tempfile, os
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")

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", "MSc", "MAS", "MSN", "MPA-URP"}
SKIP_DEG = {"BA", "BS", "B.S.", "BArch", "BFA", "Minor", "PhD", "Ph.D.", "JD",
            "MD", "DVM", "EdD", "DMA", "Certificate", "Cert", "LLM", "MTS"}


def curl(url, timeout=30):
    r = subprocess.run(["curl", "-s", "-L", "--compressed", "-A", UA,
                        "--max-time", str(timeout), url],
                       capture_output=True)
    return r.stdout.decode("utf-8", "ignore")


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("&amp;", "&").replace("&#8217;", "'").replace("&#039;", "'"))
    return "\n".join(l.strip() for l in h.split("\n") if l.strip())


def parse_list(html, prefix):
    out, 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
        nm = re.sub(r"<[^>]+>", " ", raw)
        nm = nm.replace("&nbsp;"," ").replace("&amp;","&").replace("&#8203;"," ")
        nm = re.sub(r"\s+", " ", nm).strip()
        if not nm or len(nm) > 120:
            continue
        mm = re.search(r"[\(\,]\s*([A-Za-z\.\-]{2,14})\s*\)?\s*$", nm)
        deg = mm.group(1) if mm else ""
        base = re.sub(r"[\(\,]\s*[A-Za-z\.\-]{2,14}\s*\)?\s*$", "", nm).strip()
        key = (base.lower(), deg)
        if key in seen:
            continue
        seen.add(key)
        out.append((base, deg, href))
    return out


def parse_detail(html):
    college, site, desc = "", "", ""
    m = re.search(r'<a[^>]*href="([^"]+)"[^>]*>\s*Program Website\s*</a>', html, re.I)
    if m:
        site = m.group(1)
    lines = text(html).split("\n")
    idx = None
    for i, l in enumerate(lines):
        if l.startswith("Taxonomy Codes") or l.startswith("Print Options"):
            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 ", l) and len(l) < 95:
                college = l
                break
    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, site, desc


def main():
    sid, list_url, prefix = sys.argv[1:4]
    fixed = None
    if "--college" in sys.argv:
        fixed = sys.argv[sys.argv.index("--college") + 1]
    html = curl(list_url)
    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|MEd|MSW)\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"rows={len(rows)} master={len(cand)}")

    def work(p):
        h = curl(p["url"], 25)
        if fixed:
            p["college"], p["site"], p["desc"] = fixed, "", ""
            m = re.search(r'<a[^>]*href="([^"]+)"[^>]*>\s*Program Website\s*</a>', h, re.I)
            if m:
                p["site"] = m.group(1)
        else:
            p["college"], p["site"], p["desc"] = parse_detail(h)
        return p

    with ThreadPoolExecutor(max_workers=8) 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.get("college"))
    print(f"college ok={got}/{len(out)} -> out_{sid}.json")
    for p in out[:6]:
        print(f'  {p["deg"]:<5}{p["en"][:45]:<47}{p.get("college","")[:40]}')


if __name__ == "__main__":
    main()
