"""按四类学院范围生成下一批待办队列。

在每次 quality_queue.py run 之后运行：自动排除已放行页面与已挂载的 PROGRAMS，
再按「学校优先级 → 学院优先级 → 项目名」排序，输出 scope_queue.json 与若干批次文件。

用法：python next_scope_batch.py [--root .] [--groups 4] [--size 5]
"""
import argparse
import json
import pathlib
import re


SCHOOL_ORDER = ['col', 'illinois', 'nyu', 'uw', 'usc', 'ut', 'cornell',
                'up', 'jhu', 'cmu', 'duke', 'umich', 'nu', 'ubc', 'mcg']
CLASS_ORDER = {'eng': 0, 'biz': 1, 'sci': 2, 'env': 3}

# 「文理学院」是宽口径学院，里面混有人文、社科、教育、公卫专业。
# 按用户口径，理学院只收理科 / 生命科学 / 量化方向，故用学科大类 + 项目名二次收窄。
SCI_KW = re.compile(
    r'math|statist|actuarial|physic|chem|biolog|biochem|biophys|bioinformat|genetic|genomic|'
    r'molecular|cell\b|neuro|astronom|atmospher|geolog|earth\b|environment|ecolog|comput|'
    r'data\b|quantitat|material|optic|photon|nuclear|immun|microbi|epidemiolog|geograph|'
    r'geoscien|biomedical|bioengineer', re.I)
HUMAN_KW = re.compile(
    r'african|american studies|anthropolog|archaeolog|classic|literature|history|philosophy|'
    r'religion|sociolog|political|government|economics|linguist|music|art history|theatre|'
    r'theater|dance|education|teaching|social work|journalism|media studies|communication|'
    r'\blaw\b|legal|public health|community health|health administration|nutrition|'
    r'kinesiolog|sport|recreation|tourism|hospitality|public policy|international|'
    r'gender|race|ethnic|area studies|creative writing', re.I)

# 「信息科学学院 / iSchool」因含「科学学院」会被 sci 正则误命中，
# 但图书馆学、信息管理等不属用户指定的工 / 商 / 理 / 土木环境四类。
EXCLUDE_COLLEGE = re.compile(r'信息科学学院|iSchool|图书馆学', re.I)
# 项目名层面的边界项：社科 / 健康科学 / 农业与生命科学按 focus_scope.json 的
# boundary 约定「单列待确认」，本轮不进入四类核验队列（条目仍保留在库中）。
EXCLUDE_NAME = re.compile(
    r'library|librarian|information management|knowledge management|'
    r'political science|speech\s*&\s*hearing|psychological science|'
    r'animal sciences|animal studies|crop sciences|soil and crop|food science', re.I)


def in_scope(item):
    """排除人文 / 社科 / 教育 / 公卫等非四类方向，保留被误标到这些大类的理科项目。"""
    if EXCLUDE_COLLEGE.search(str(item.get('college', ''))) or EXCLUDE_NAME.search(item['en']):
        return False
    if item['disc'] in ('art', 'soc', 'edu', 'med'):
        name = item['en']
        return bool(SCI_KW.search(name)) and not HUMAN_KW.search(name)
    return True


def atomic_write(path, text):
    """先写临时文件再替换：Windows 下直接覆盖可能被 ACL 或索引服务拒绝。"""
    tmp = path.with_suffix(path.suffix + '.new')
    tmp.write_text(text, encoding='utf-8')
    try:
        tmp.replace(path)
    except PermissionError:
        path.unlink(missing_ok=True)
        tmp.replace(path)


def js_array(text, name):
    mark = 'const ' + name + '=['
    start = text.find(mark)
    if start < 0:
        raise ValueError('找不到 ' + mark)
    i = start + len(mark) - 1
    depth, quote, esc = 0, None, False
    while i < len(text):
        c = text[i]
        if quote:
            if esc:
                esc = False
            elif c == '\\':
                esc = True
            elif c == quote:
                quote = None
        elif c in '"\'`':
            quote = c
        elif c == '[':
            depth += 1
        elif c == ']':
            depth -= 1
            if depth == 0:
                raw = text[start + len(mark) - 1:i + 1]
                raw = re.sub(r',\s*([\]}])', r'\1', raw)
                return json.loads(raw)
        i += 1
    raise ValueError(name + ' 数组未闭合')


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--root', default='.')
    ap.add_argument('--groups', type=int, default=4)
    ap.add_argument('--size', type=int, default=5)
    args = ap.parse_args()
    root = pathlib.Path(args.root).resolve()

    html = (root / 'index_main.html').read_text(encoding='utf-8')
    catd = js_array(html, 'CATD')
    scope = json.loads((root / 'focus_scope.json').read_text(encoding='utf-8'))
    report = json.loads((root / 'quality_report.json').read_text(encoding='utf-8'))
    schools = {m[0]: m[1] for m in re.findall(
        r'\{id:"([^"]+)",cn:"([^"]+)"', html)}

    passed = {
        item['record']['detail']
        for item in report['items']
        if (item.get('result') or {}).get('page_status') == 'pass'
        and item['record'].get('detail')
    }
    mounted = set(re.findall(r'url:"(details/[^"]+\.html)"', html))
    rules = scope['rules']

    def classify(college):
        c = str(college or '')
        for key in ('biz', 'env', 'eng', 'sci'):
            if re.search(rules[key]['re'], c):
                return key
        return None

    queue = []
    for i, c in enumerate(catd):
        cls = classify(c[1])
        if not cls:
            continue
        detail = c[7]
        if detail in passed or detail in mounted:
            continue
        item = dict(key='CATD:' + str(i), id='cat' + str(i), school=c[0],
                    cn_school=schools.get(c[0], c[0]), college=c[1], cls=cls,
                    en=c[2], cn=c[3], degree=c[4], url=c[5], disc=c[6],
                    detail=detail)
        if not in_scope(item):
            continue
        queue.append(item)
    queue.sort(key=lambda x: (SCHOOL_ORDER.index(x['school']) if x['school'] in SCHOOL_ORDER else 99,
                              CLASS_ORDER.get(x['cls'], 9), x['en']))
    atomic_write(root / 'scope_queue.json',
                 json.dumps(queue, ensure_ascii=False, indent=1))

    for g in range(args.groups):
        batch = queue[g * args.size:(g + 1) * args.size]
        if not batch:
            break
        path = root / f'scope_b{g + 1:02d}.json'
        atomic_write(path, json.dumps(batch, ensure_ascii=False, indent=1))
        print(f'{path.name}: {len(batch)} 条 | ' + ', '.join(x['en'][:24] for x in batch))
    print(f'四类待办剩余 {len(queue)} 条；已放行 {len(passed)} 个页面')
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
