#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""把 harvest 结果转成 CATD 行：["sid","学院","EN","中文","学位","URL","disc"]"""
import json, re, sys
from tr import tr

DISC_RULES = [
    ("cs", r"Computer|Information Science|Information Systems|Data Science|Robotics|Computational|Software|Machine Learning|Artificial Intelligence|Cybersecurity"),
    ("eng", r"Engineering|Aerospace|Mechanical|Electrical|Civil|Chemical|Materials|Systems|Operations Research|Nuclear|Petroleum"),
    ("biz", r"Human Resources|Management|Business|MBA|Finance|Accounting|Marketing|Real Estate|Hospitality|Hotel|Labor Relations|Entrepreneur|Supply Chain"),
    ("sci", r"Horticultur|Plant |Plant$|Soil|Entomolog|Crop|Food Science"),
    ("med", r"Child Health|Community Health|Mental Health|Health Technology|Public Health|Health Administration|Health Policy|Biomedical|Biolog|Veterinary|Neuroscience|Biophysics|Nutrition|Epidemiolog|Nursing|Medicine|Dent|Pharm"),
    ("art", r"Image Text|Architecture|Design|Art|Music|Theatre|Writing|Film|Media|Landscape|Creative|Fashion|Apparel|Museum|Preservation"),
    ("edu", r"Education|Teaching|Curriculum|Instruction"),
    ("sci", r"Physics|Chemistry|Mathematics|Statistics|Geolog|Earth|Atmospheric|Astronomy|Entomolog|Plant|Soil|Food Science|Natural Resources|Science"),
    ("soc", r"Policy|Public Administration|Economics|Political|Sociolog|Anthropolog|Psycholog|History|Philosoph|Religion|Linguist|Law|Legal|Development|Studies|Relations|Human|Global|Government|Criminolog|Social Work|Geography|Planning"),
]


OVERRIDE = {
    "Management (w/ Tsinghua U-China)": "管理（清华合作项目）",
    "Management (w/& Tsinghua U-&China)": "管理（清华合作项目）",
    "Executive MBA": "高级工商管理硕士（EMBA）",
    "Executive MPA": "高级公共管理硕士（EMPA）",
    "Executive MHA": "高级健康管理硕士",
    "Management, 2 year": "管理学（两年制）",
    "Management Science, 2 Year": "管理科学（两年制）",
    "Systems": "系统学",
    "Regional Science": "区域科学",
    "Design Technology: Studio": "设计技术（工作室方向）",
    "Agriculture and Life Sciences": "农业与生命科学",
}


def disc(name, college):
    for d, pat in DISC_RULES:
        if re.search(pat, name, re.I):
            return d
    if "商学院" in college:
        return "biz"
    if "工程学院" in college:
        return "eng"
    if "法学院" in college:
        return "soc"
    return "soc"


def main(sid, path, out):
    d = json.load(open(path, encoding="utf-8"))
    rows = []
    for p in d:
        en = p["en"].replace("-&#8203;", "- ").replace("&#8203;", "&").replace("&amp;", "&").replace("\u200b", "")
        en = re.sub(r"\s+", " ", en).strip()
        deg = p["deg"]
        url = p.get("site") or p["url"]
        col = p.get("col") or p.get("college") or "研究生院"
        cn = OVERRIDE.get(en) or tr(en)
        rows.append([sid, col, en, cn, deg, url, disc(en, col)])
    # 去重（同名同学位）
    seen = set()
    uniq = []
    for r in rows:
        k = (r[2].lower(), r[4])
        if k in seen:
            continue
        seen.add(k)
        uniq.append(r)
    uniq.sort(key=lambda r: (r[1], r[2]))
    with open(out, "w", encoding="utf-8") as f:
        for r in uniq:
            f.write('["%s", "%s", "%s", "%s", "%s", "%s", "%s"],\n' % tuple(r))
    print(f"{sid}: {len(rows)} -> {len(uniq)} rows  => {out}")
    for r in uniq[:10]:
        print(f"   {r[4]:<6}{r[2][:38]:<40}{r[3][:26]:<28}{r[6]}  | {r[1]}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2], sys.argv[3])
