#!/usr/bin/env python
"""离线网页质检与有限队列；不执行页面脚本、生成器或队列中的命令。"""
import argparse
import datetime as dt
import hashlib
import html
from html.parser import HTMLParser
import json
import os
import posixpath
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unicodedata
from urllib.parse import unquote, urlsplit

VERSION = '1.0'
SECTIONS = ('申请要求', '费用', '课程设置', '培养方案', '院校与城市', '官方链接')
REQUIRED = {'申请要求': ('申请截止', '语言', '标化', '学术背景', '申请材料'),
            '费用': ('学费', '生活'), '院校与城市': ('城市', '就业', '薪资', '生活')}
VOID = {'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'}


def issue(code, message, level='error', **extra):
    return dict(code=code, message=message, level=level, **extra)


class Node:
    def __init__(self, tag='', attrs=(), parent=None, line=1):
        self.tag, self.attrs, self.parent, self.line = tag, dict(attrs), parent, line
        self.children = []

    def walk(self):
        yield self
        for c in self.children:
            if isinstance(c, Node):
                yield from c.walk()

    def text(self):
        if self.tag in ('script', 'style'):
            return ''
        return ''.join(c.text() if isinstance(c, Node) else c for c in self.children)

    def raw_text(self):
        return ''.join(c.raw_text() if isinstance(c, Node) else c for c in self.children)


class Document(HTMLParser):
    def __init__(self, source):
        super().__init__(convert_charrefs=True)
        self.root = Node()
        self.current = self.root
        self.feed(source)
        self.close()

    def handle_starttag(self, tag, attrs):
        n = Node(tag, attrs, self.current, self.getpos()[0])
        self.current.children.append(n)
        if tag not in VOID:
            self.current = n

    def handle_startendtag(self, tag, attrs):
        self.handle_starttag(tag, attrs)
        if tag not in VOID:
            self.handle_endtag(tag)

    def handle_endtag(self, tag):
        n = self.current
        while n.parent:
            if n.tag == tag:
                self.current = n.parent
                return
            n = n.parent

    def handle_data(self, text):
        self.current.children.append(text)


def external(value):
    u = urlsplit(value)
    return u.scheme in ('https', 'http') and bool(u.hostname)


def sources(node):
    return sorted({n.attrs['href'] for n in node.walk()
                   if n.tag == 'a' and external(n.attrs.get('href', ''))})


def _ancestors(node):
    cur = node.parent
    while cur is not None:
        yield cur
        cur = cur.parent


def card_of(node):
    """向上找最近的内容卡（class 含 card）。页脚 yellow 说明不算来源容器。"""
    cur = node.parent
    while cur is not None:
        classes = cur.attrs.get('class', '').split()
        if 'card' in classes:
            return cur
        cur = cur.parent
    return None


def card_sources(node):
    """字段所在内容卡内的官方外链；与标杆页（哥大 CS）一致：来源按卡片锚定。"""
    card = card_of(node)
    if card is None:
        return [], False
    editorial = '编辑整理' in card.text()
    return sources(card), editorial


def field_evidence(node):
    """先看字段自身邻接链接；没有再回退到所在内容卡的链接。
    返回 (sources, scope)；scope 为 field / card / editorial / none。"""
    direct = sources(node)
    if direct:
        return direct, 'field'
    card, editorial = card_sources(node)
    if card:
        return card, 'card'
    if editorial:
        return [], 'editorial'
    return [], 'none'


def norm(text):
    return re.sub(r'[^\w\u4e00-\u9fff]', '', unicodedata.normalize('NFKC', text).casefold())


def norm_url(value):
    u = urlsplit(unquote(value.replace('\\', '/')))
    return (u.netloc.casefold(), posixpath.normpath(re.sub('/+', '/', u.path)).rstrip('/'), u.query)


class LiteralParser:
    """仅接受 JSON 风格字面量及未加引号的对象键；绝不 eval/执行 JS。"""
    def __init__(self, text, pos):
        self.text, self.pos = text, pos

    def skip(self):
        while True:
            m = re.match(r'(?:\s+|/\*.*?\*/|//[^\n]*(?:\n|$))', self.text[self.pos:], re.S)
            if not m:
                return
            self.pos += m.end()

    def value(self):
        self.skip()
        c = self.text[self.pos:self.pos + 1]
        if c == '"':
            value, end = json.JSONDecoder().raw_decode(self.text[self.pos:])
            self.pos += end
            return value
        if c in ('[', '{'):
            self.pos += 1
            out = [] if c == '[' else {}
            close = ']' if c == '[' else '}'
            self.skip()
            while self.text[self.pos:self.pos + 1] != close:
                if c == '{':
                    self.skip()
                    if self.text[self.pos:self.pos + 1] == '"':
                        key = self.value()
                    else:
                        m = re.match(r'[A-Za-z_$][\w$]*', self.text[self.pos:])
                        if not m:
                            raise ValueError('不支持的对象键')
                        key = m[0]
                        self.pos += m.end()
                    self.skip()
                    if self.text[self.pos:self.pos + 1] != ':':
                        raise ValueError('对象缺少冒号')
                    self.pos += 1
                    if key in out:
                        raise ValueError('重复对象键：' + key)
                    out[key] = self.value()
                else:
                    out.append(self.value())
                self.skip()
                if self.text[self.pos:self.pos + 1] == close:
                    break
                if self.text[self.pos:self.pos + 1] != ',':
                    raise ValueError('仅支持静态字面量，拒绝表达式')
                self.pos += 1
                self.skip()
            self.pos += 1
            return out
        m = re.match(r'(true|false|null|-?\d+(?:\.\d+)?)\b', self.text[self.pos:])
        if not m:
            raise ValueError('拒绝非字面量数据')
        self.pos += m.end()
        return json.loads(m[0])


def literal(source, name):
    m = re.search(r'\bconst\s+' + re.escape(name) + r'\s*=', source)
    if not m:
        raise ValueError('缺少数据常量 ' + name)
    return LiteralParser(source, m.end()).value()


def local_target(root, page, href):
    if not href or href.startswith('#'):
        return None
    u = urlsplit(href)
    if u.scheme or u.netloc:
        return None
    if not u.path:
        return None
    path = unquote(u.path).replace('\\', '/')
    target = (root / path.lstrip('/') if path.startswith('/') else page.parent / path).resolve()
    if not target.is_relative_to(root.resolve()):
        raise ValueError('本地链接越出项目根目录')
    return target


def href_issues(root, page, doc):
    out = []
    for n in doc.root.walk():
        if 'href' not in n.attrs:
            continue
        href = n.attrs['href']
        try:
            target = local_target(root, page, href)
            if target is not None and not target.is_file():
                out.append(issue('missing_local_href', '本地 href 文件不存在', href=href, line=n.line))
        except ValueError as e:
            out.append(issue('unsafe_local_href', str(e), href=href, line=n.line))
    return out


def has_editorial_data(text):
    """是否存在真正的非官方数据标注；官方 “estimated cost of attendance（估算口径）” 与否定表述不算。"""
    for m in re.finditer(r'编辑整理|市场区间|估算', text):
        ctx = text[max(0, m.start() - 10):m.start() + 14]
        if re.search(r'不做估算|无估算|不估算|不采用估算|避免估算|不做.{0,4}估算', ctx):
            continue
        if re.search(r'官方.{0,6}估算|估算口径|SFS.{0,6}估算|estimated', ctx, re.I):
            continue
        return True
    return False


def semantic_issues(text, year, line=1):
    out = []
    # 裸占位符是真缺陷；"本次未取得/官网未公布"是合格的诚实标注，只作提示。
    if re.search(r'TODO|TBD|__\w+__|待填|此处填|占位符', text, re.I):
        out.append(issue('placeholder_content', '含未替换的占位符', line=line))
    if re.search(r'待.{0,8}(核验|补充|确认|更新)|本次未取得|官网未公布|未取得', text, re.I):
        out.append(issue('declared_gap', '已声明信息缺口（官网未公布/本次未取得）', 'info', line=line))
    # 只有"声称已全部核验"才算夸大；"不作全量核验宣称"这类否定句是诚实标注。
    claim = re.search(r'(全部.{0,12}(官网|官方)|全量.{0,8}(完成|核验)|仅收录已核验|全部字段核验完成)', text)
    if claim:
        head = text[max(0, claim.start() - 14):claim.start()]
        negated = re.search(r'(不作|不宣称|不做|不得|不能|不予|并非|避免|不算|未作|未宣称|不视为)', head)
        if not negated:
            out.append(issue('unverified_claim', '全量或已核验宣称不能由离线检查证实，须人工核验', 'review', line=line))
    for match in re.finditer(r'\b(20\d{2})\s*[-–/]\s*(\d{2}|20\d{2})\s*(?:学年|官方|费率)?', text):
        end_year = int(match[2]) if len(match[2]) == 4 else 2000 + int(match[2])
        if end_year == int(match[1]) + 1 and end_year < year:
            level = 'info' if re.search(r'仅|截至|边界|未公布|未取得|旧|上一年', text) else 'review'
            out.append(issue('old_cycle', '出现旧学年周期，需确认是否适用于目标申请季', level, value=match[0], line=line))
    for match in re.finditer(r'\b(20\d{2})\s*(?:年)?\s*(秋|春|夏|冬|申请季)', text):
        if int(match[1]) < year:
            level = 'info' if re.search(r'仅|截至|边界|未公布|未取得|旧|上一年', text) else 'review'
            out.append(issue('old_admission_cycle', '出现旧入学/申请周期', level, value=match[0], line=line))
    if re.search(r'(?:全部|均(?![分衡值]))(?![分衡值]).{0,15}(官网|官方)', text) and has_editorial_data(text):
        out.append(issue('contradictory_label', '全部官方来源宣称与编辑整理/估算标注并存', line=line))
    if re.search(r'(已核验|核验完成|全部完成)', text) and re.search(r'待.{0,8}核验|核验前', text):
        if not re.search(r'(不把|不得|不能|避免|不算|并非).{0,12}(说成|视为|等同)', text):
            out.append(issue('contradictory_verification', '已核验与待核验标注并存', line=line))
    return out


def audit_page(root, relative, year):
    path = root / relative
    out, fields = [], []
    if not path.is_file():
        return dict(status='fail', issues=[issue('missing_page', '详情页不存在')], fields=[])
    doc = Document(path.read_text(encoding='utf-8-sig'))
    out.extend(href_issues(root, path, doc))
    headings = [n for n in doc.root.walk() if n.tag == 'h2']
    for title in SECTIONS:
        if not any(title in h.text() for h in headings):
            out.append(issue('missing_section', '缺少章节：' + title))
    if not any(n.tag == 'h1' and n.text().strip() for n in doc.root.walk()):
        out.append(issue('missing_title', '缺少项目标题'))
    for heading in headings:
        section = heading.parent
        text = section.text()
        if '官方链接' in heading.text():
            if not sources(section):
                out.append(issue('missing_official_links', '官方链接章节无外部来源链接', line=heading.line))
            continue
        for title, labels in REQUIRED.items():
            if title in heading.text():
                for label in labels:
                    if label not in text.replace(heading.text(), '', 1):
                        out.append(issue('missing_required', '缺少必填内容：' + title + '/' + label, line=heading.line))
        candidates = [n for n in section.walk() if n.tag in ('tr', 'li') or
                      (n.tag in ('div', 'p') and set(n.attrs.get('class', '').split()) & {'info', 'ptext', 'pdesc'})]
        if not candidates:
            candidates = [n for n in section.walk() if n.tag == 'p']
        if not candidates:
            candidates = [section]
        for field in candidates:
            value = field.text().replace(heading.text(), '', 1).strip()
            evidence, scope = (field_evidence(field) if field is not section else ([], 'none'))
            entry = dict(section=heading.text(), label=value[:140], line=field.line,
                         sources=evidence, scope=scope)
            fields.append(entry)
            if not value or len(value) < 3:
                out.append(issue('empty_field', '内容为空或过短', line=field.line))
            if not evidence and scope == 'editorial':
                continue  # 编辑整理卡已标注非官方来源，不作为字段级缺证
            if not evidence and scope == 'none':
                out.append(issue('missing_field_source', '字段与所在卡片均无官方链接：' + value[:85], 'review', line=field.line))
            elif scope == 'card':
                out.append(issue('source_anchored_to_card', '来源按卡片锚定（与标杆页一致）：' + value[:60], 'info', line=field.line))
    for field in doc.root.walk():
        if field.tag == 'h1' or set(field.attrs.get('class', '').split()) & {'en', 'school', 'badge', 'rank'}:
            evidence, scope = field_evidence(field)
            fields.append(dict(section='项目基本信息', label=field.text().strip()[:140],
                               line=field.line, sources=evidence, scope=scope))
            # 封面信息（hero）是页面标题区，不是数据字段，不要求外链锚定。
            in_hero = any(isinstance(a, Node) and 'hero' in a.attrs.get('class', '').split()
                          for a in _ancestors(field))
            if not evidence and scope == 'none' and not in_hero:
                out.append(issue('missing_field_source', '基本信息字段与所在卡片均无官方链接：' + field.text().strip()[:85], 'review', line=field.line))
    out.extend(semantic_issues(doc.root.text(), year))
    status = 'fail' if any(x['level'] == 'error' for x in out) else (
        'review' if any(x['level'] == 'review' for x in out) else 'pass')
    return dict(status=status, issues=out, fields=fields,
                limitation='来源链接仅检查邻近性，不代表已联网核验来源真实性或时效性')


def check_js(doc):
    out = []
    node = shutil.which('node')
    if not node:
        return [issue('node_unavailable', '未找到 node，首页 JS 语法检查阻塞')]
    for i, script in enumerate(n for n in doc.root.walk() if n.tag == 'script'):
        if script.attrs.get('src'):
            out.append(issue('external_script_unchecked', '外部脚本未执行且未检查', 'review', script=i))
            continue
        if script.attrs.get('type', '') not in ('', 'text/javascript', 'application/javascript', 'module'):
            continue
        args = [node, '--check']
        if script.attrs.get('type') == 'module':
            args.append('--input-type=module')
        args.append('-')
        try:
            run = subprocess.run(args, input=script.raw_text(), text=True, encoding='utf-8',
                                 capture_output=True, timeout=30, shell=False)
            if run.returncode:
                out.append(issue('js_syntax_error', run.stderr[:4000], script=i))
        except (OSError, subprocess.TimeoutExpired) as e:
            out.append(issue('js_check_blocked', str(e), script=i))
    return out


def same_project_name(a, b):
    """同一项目的宽松同名判定：去括注、去学位后缀后一方包含另一方即可。"""
    def simplify(x):
        x = re.sub(r'\([^)]*\)', '', str(x))
        x = re.sub(r'\b(MS|MA|MPA|MBA|MIA|PhD|MPS|MFA|MEd|MPH)\b', '', x, flags=re.I)
        return norm(x)
    x, y = simplify(a), simplify(b)
    if not x or not y:
        return False
    return x == y or x in y or y in x


def inventory(root):
    source = (root / 'index_main.html').read_text(encoding='utf-8-sig')
    schools, programs, catalog = (literal(source, x) for x in ('SCHOOLS', 'PROGRAMS', 'CATD'))
    school_map = {s['id']: norm(s['cn']) for s in schools}
    records, out = [], []
    for p in programs:
        records.append(dict(key='PROGRAMS:' + str(len(records)), id=p.get('id'), school=p.get('s'),
                            name=p.get('en', ''), degree=p.get('deg', ''), detail=p.get('url', ''), origin='PROGRAMS'))
    for i, c in enumerate(catalog):
        if len(c) < 8:
            out.append(issue('catalog_missing_detail', '目录条目缺少详情路径', row=i))
            continue
        records.append(dict(key='CATD:' + str(i), id='cat' + str(i), school=c[0], name=c[2],
                            degree=c[4], detail=c[7], origin='CATD'))
    seen_id, seen_url, seen_name = {}, {}, {}
    for r in records:
        if r['school'] not in school_map:
            out.append(issue('unknown_school', '不属于当前首页学校范围', records=[r['key']]))
        if r['origin'] == 'PROGRAMS':
            if r['id'] in seen_id:
                out.append(issue('duplicate_program_id', 'PROGRAMS ID 重复', records=[seen_id[r['id']], r['key']]))
            seen_id[r['id']] = r['key']
        school = school_map.get(r['school'], norm(str(r['school'])))
        # 同一项目跨层指向同一核验页属"目录条目升级"，不是重复；不同项目指向同一页才是错。
        for mapping, key, code in ((seen_url, (school, norm_url(r['detail'])), 'duplicate_detail_url'),
                                   (seen_name, (school, norm(r['name']), norm(r['degree'])), 'duplicate_school_program')):
            previous = mapping.get(key)
            if previous:
                same_project = same_project_name(previous['name'], r['name'])
                # 仅豁免"同项目跨层指向同一核验页"（目录条目已升级为核验页）；
                # 同层内不同条目指向同一页仍属重复。
                if (code == 'duplicate_detail_url' and same_project
                        and previous['origin'] != r['origin']):
                    continue
                out.append(issue(code, '同学校同项目重复（含 PROGRAMS/CATD 交叉）', records=[previous['key'], r['key']],
                                 cross_layer=previous['origin'] != r['origin']))
            else:
                mapping[key] = r
    doc = Document(source)
    out.extend(href_issues(root, root / 'index_main.html', doc))
    out.extend(check_js(doc))
    out.extend(semantic_issues(doc.root.text(), dt.date.today().year))
    return records, out, len(schools), len(programs), len(catalog)


def atomic_json(path, data):
    fd, temp = tempfile.mkstemp(prefix=path.name + '.', suffix='.tmp', dir=path.parent)
    try:
        with os.fdopen(fd, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
            f.flush()
            os.fsync(f.fileno())
        os.replace(temp, path)
    finally:
        if os.path.exists(temp):
            os.unlink(temp)


def fingerprint(root, detail, year):
    digest = hashlib.sha256()
    for label, data in [('rule', Path(__file__).read_bytes()), ('year', str(year).encode()),
                        ('index', (root / 'index_main.html').read_bytes())]:
        digest.update(label.encode() + b'\0' + data)
    try:
        path = local_target(root, root / 'index_main.html', detail)
        if path is None:
            raise ValueError('详情路径必须为项目内本地文件')
        digest.update(path.read_bytes() if path.is_file() else b'MISSING')
        if path.is_file():
            doc = Document(path.read_text(encoding='utf-8-sig'))
            for n in doc.root.walk():
                if 'href' in n.attrs:
                    target = local_target(root, path, n.attrs['href'])
                    if target:
                        digest.update(str(target).encode())
                        digest.update(target.read_bytes() if target.is_file() else b'MISSING')
    except (ValueError, OSError) as e:
        digest.update(str(e).encode())
    return digest.hexdigest()


def run_queue(root, batch_size=50, max_batches=None, year=None):
    root = Path(root).resolve()
    year = year or dt.date.today().year + 1
    records, global_issues, schools, programs, catalog = inventory(root)
    state_path = root / 'quality_queue_state.json'
    old = json.loads(state_path.read_text(encoding='utf-8')) if state_path.exists() else {}
    old_items = old.get('items', {})
    gate_hash = hashlib.sha256(json.dumps(global_issues, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
    items, invalidated = {}, 0
    for r in records:
        fp = fingerprint(root, r['detail'], year)
        previous = old_items.get(r['key'], {})
        unchanged = (previous.get('hash') == fp and previous.get('record') == r
                     and old.get('gate_hash') == gate_hash)
        if previous and not unchanged:
            invalidated += 1
        items[r['key']] = previous if unchanged else dict(record=r, hash=fp, state='pending', approval=False, attempts=0)
    state = dict(version=VERSION, target_year=year, gate_hash=gate_hash, items=items, invalidated=invalidated)
    def save():
        state['updated_at'] = dt.datetime.now(dt.timezone.utc).isoformat()
        atomic_json(state_path, state)
    save()
    todo = [v for v in items.values() if v['state'] == 'pending']
    batches = 0
    global_block = any(x['level'] == 'error' and 'records' not in x for x in global_issues)
    for start in range(0, len(todo), batch_size):
        if max_batches is not None and batches >= max_batches:
            break
        for item in todo[start:start + batch_size]:
            r = item['record']
            try:
                target = local_target(root, root / 'index_main.html', r['detail'])
                if target is None:
                    raise ValueError('仅处理项目内本地详情文件')
                result = audit_page(root, target.relative_to(root).as_posix(), year)
                result['page_status'] = result['status']
                related = [x for x in global_issues if r['key'] in x.get('records', [])]
                result['issues'].extend(related)
                if global_block:
                    result['issues'].append(issue('homepage_gate_blocked', '首页存在全局错误，禁止批准'))
                if any(x['level'] == 'error' for x in result['issues']):
                    result['status'] = 'fail'
                elif any(x['level'] == 'review' for x in result['issues']):
                    result['status'] = 'review'
                if fingerprint(root, r['detail'], year) != item['hash']:
                    result['status'] = 'fail'
                    result['issues'].append(issue('changed_during_audit', '检查期间文件变化，下次运行重新检查'))
            except (OSError, ValueError, IndexError) as e:
                result = dict(status='fail', issues=[issue('audit_blocked', str(e))], fields=[])
            item.update(result=result, state='completed' if result['status'] == 'pass' else 'blocked',
                        approval=result['status'] == 'pass', attempts=item['attempts'] + 1)
            save()
        batches += 1
    counts = {name: sum(v['state'] == name for v in items.values()) for name in ('completed', 'blocked', 'pending')}
    counts.update(review=sum(v.get('result', {}).get('status') == 'review' for v in items.values()),
                  fail=sum(v.get('result', {}).get('status') == 'fail' for v in items.values()),
                  page_review=sum(v.get('result', {}).get('page_status') == 'review' for v in items.values()),
                  page_fail=sum(v.get('result', {}).get('page_status') == 'fail' for v in items.values()),
                  page_pass=sum(v.get('result', {}).get('page_status') == 'pass' for v in items.values()))
    report = dict(version=VERSION, generated_at=state['updated_at'], target_year=year,
                  scope='仅首页现有学校与 PROGRAMS/CATD 项目；不生成或修改项目数据',
                  limitations=['pass 仅表示离线规则通过，不代表官网事实已独立核验',
                               '不执行生成器、页面 JS 或队列提供的命令；Node 仅 stdin --check',
                               '待核验项归入 blocked，保留 review 状态；文件/规则/首页/本地来源变化后失效重检',
                               '静态关键词检查不替代人工语义核验；不爬网、不补造数据'],
                  totals=dict(schools=schools, programs=programs, catalog=catalog, queue=len(items), **counts),
                  checks=dict(homepage_js='blocked' if any(x['code'].startswith(('js_', 'node_', 'external_script')) for x in global_issues) else 'pass',
                              program_id_duplicates=sum(x['code'] == 'duplicate_program_id' for x in global_issues),
                              duplicate_detail_urls=sum(x['code'] == 'duplicate_detail_url' for x in global_issues),
                              missing_local_hrefs=sum(x['code'] == 'missing_local_href' for x in global_issues) +
                                  sum(x['code'] == 'missing_local_href' for v in items.values() for x in v.get('result', {}).get('issues', []))),
                  batches_this_run=batches, invalidated=invalidated, global_issues=global_issues,
                  queue_exhausted=counts['pending'] == 0,
                  all_approved=counts['completed'] == len(items) and not global_issues,
                  items=list(items.values()))
    atomic_json(root / 'quality_report.json', report)
    write_html(root / 'quality_report.html', report)
    return report


def write_html(path, report):
    esc = lambda x: html.escape(str(x), quote=True)
    rows = []
    for item in report['items']:
        r = item['record']
        result = item.get('result', {})
        reasons = ''.join('<li>' + esc(x['code'] + '：' + x['message']) + '</li>' for x in result.get('issues', []))
        rows.append('<tr><td>' + esc(r['key']) + '<br>' + esc(r['detail']) + '</td><td>' + esc(r['name']) +
                    '</td><td>' + esc(item['state']) + '/' + esc(result.get('status', 'pending')) +
                    '</td><td><details><summary>问题 ' + str(len(result.get('issues', []))) +
                    '</summary><ul>' + reasons + '</ul></details></td></tr>')
    global_list = ''.join('<li>' + esc(x['code'] + '：' + x['message']) + '</li>' for x in report['global_issues'])
    page = '<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>网页质检与队列报告</title>'
    page += '<style>body{font:15px/1.7 system-ui;margin:32px;color:#183047}table{border-collapse:collapse;width:100%}td,th{border:1px solid #cad5df;padding:10px;text-align:left;vertical-align:top}summary{cursor:pointer}li{overflow-wrap:anywhere}</style>'
    page += '<h1>网页质检与队列报告</h1><p>审核通过 completed/pass；待核验 blocked/review；硬错误 blocked/fail；未处理 pending。</p>'
    page += '<p><b>扫描队列耗尽不等于全量审核通过。</b> 此工具只消费已有网页审核任务，不执行内容生成或权限操作。</p>'
    page += '<p>' + esc(report['generated_at']) + ' · 目标申请季 ' + esc(report['target_year']) + '</p>'
    page += '<pre>' + esc(json.dumps(report['totals'], ensure_ascii=False, indent=2)) + '</pre>'
    page += '<p>全量批准：' + esc(report['all_approved']) + '；队列耗尽：' + esc(report['queue_exhausted']) + '</p>'
    page += '<ul>' + ''.join('<li>' + esc(x) + '</li>' for x in report['limitations']) + '</ul>'
    page += '<h2>专项检查</h2><pre>' + esc(json.dumps(report['checks'], ensure_ascii=False, indent=2)) + '</pre>'
    page += '<h2>首页与数据层问题</h2><ul>' + global_list + '</ul>'
    page += '<h2>逐项结果</h2><table><tr><th>任务/文件</th><th>项目</th><th>状态</th><th>问题</th></tr>' + ''.join(rows) + '</table></html>'
    path.write_text(page, encoding='utf-8')


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('command', choices=['run'])
    p.add_argument('--root', type=Path, default=Path(__file__).resolve().parent)
    p.add_argument('--batch-size', type=int, default=50)
    p.add_argument('--max-batches', type=int)
    p.add_argument('--target-year', type=int, default=dt.date.today().year + 1)
    args = p.parse_args()
    if args.batch_size < 1 or (args.max_batches is not None and args.max_batches < 1):
        p.error('批次大小和批次数必须为正整数')
    # 锁只作并发排他；崩溃后的旧锁不自动删除，避免越权覆盖其他进程。
    lock = args.root / 'quality_queue.lock'
    try:
        fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except FileExistsError:
        p.error('队列锁已存在，请先确认是否有运行中进程；不会自动删除锁')
    try:
        os.close(fd)
        report = run_queue(args.root, args.batch_size, args.max_batches, args.target_year)
        print(json.dumps(dict(totals=report['totals'], global_issues=len(report['global_issues']),
                              batches=report['batches_this_run'], all_approved=report['all_approved']), ensure_ascii=False))
    finally:
        lock.unlink()


if __name__ == '__main__':
    main()
