#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""青禾市城市名片 —— 静态检查脚本（不启动浏览器、不联网、不写任何文件）。

用法
----
    python3 verify.py

检查项
------
1. 成品文件存在且非空
2. 输入文件 SHA256 与 input-sha256.json 一致（原始输入未被改动）
3. HTML 完全离线：无 http(s)/协议相对外链、无远程脚本样式图片
4. 无照片素材：无 <img>、无外部背景图
5. 六个资料编号、六个指标名与六个数值都出现在页面中
6. 三个板块（概览 / 文化 / 生活）齐备
7. 虚构声明出现在页面首屏与打印样式区，并出现在来源对照.md
8. JS 失效兜底：每个 .num 的静态文本 == data-value（数字不会恒为 0）
9. 打印样式存在且展开全部板块；打印时数值由 data-value 强制输出
10. prefers-reduced-motion 支持
11. 动画开关与暂停/继续控件存在
12. 刻度条填充值在 0–100 之间
13. HTML 标签闭合
14. 内联 JS 语法（node --check，若可用）
15. 幂等性：重新渲染的字节与磁盘上的成品一致
"""

from __future__ import annotations

import hashlib
import re
import subprocess
import sys
from html.parser import HTMLParser
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
sys.path.insert(0, str(HERE))

import generate  # noqa: E402  (同目录脚本，作为可复用模块导入)

HTML_PATH = HERE / generate.HTML_NAME
MD_PATH = HERE / generate.MD_NAME

VOID_TAGS = {
    "area", "base", "br", "col", "embed", "hr", "img", "input",
    "link", "meta", "param", "source", "track", "wbr",
}

RESULTS: list[tuple[bool, str, str]] = []


def check(ok: bool, name: str, detail: str = "") -> bool:
    RESULTS.append((bool(ok), name, detail))
    return bool(ok)


class TagChecker(HTMLParser):
    """轻量标签闭合检查（不做 HTML5 隐式闭合推断，只查显式配对）。"""

    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.stack: list[tuple[str, tuple[int, int]]] = []
        self.errors: list[str] = []

    def handle_starttag(self, tag, attrs):
        if tag not in VOID_TAGS:
            self.stack.append((tag, self.getpos()))

    def handle_endtag(self, tag):
        if tag in VOID_TAGS:
            return
        if not self.stack:
            self.errors.append(f"多余结束标签 </{tag}> @ {self.getpos()}")
            return
        if self.stack[-1][0] == tag:
            self.stack.pop()
            return
        for i in range(len(self.stack) - 1, -1, -1):
            if self.stack[i][0] == tag:
                unclosed = [t for t, _ in self.stack[i + 1:]]
                self.errors.append(f"</{tag}> 处存在未闭合标签 {unclosed} @ {self.getpos()}")
                del self.stack[i:]
                return
        self.errors.append(f"多余结束标签 </{tag}> @ {self.getpos()}")

    def finish(self) -> list[str]:
        super().close()
        if self.stack:
            self.errors.append(f"未闭合标签 {[t for t, _ in self.stack]}")
        return self.errors


def sha256_of(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main() -> int:
    # 1. 成品存在
    check(HTML_PATH.exists() and HTML_PATH.stat().st_size > 0, "成品 HTML 存在且非空",
          f"{HTML_PATH.name} {HTML_PATH.stat().st_size if HTML_PATH.exists() else 0} 字节")
    check(MD_PATH.exists() and MD_PATH.stat().st_size > 0, "成品 Markdown 存在且非空",
          f"{MD_PATH.name} {MD_PATH.stat().st_size if MD_PATH.exists() else 0} 字节")
    if not (HTML_PATH.exists() and MD_PATH.exists()):
        report()
        return 2

    html_text = HTML_PATH.read_text(encoding="utf-8")
    md_text = MD_PATH.read_text(encoding="utf-8")

    # 2. 输入未被改动
    ok_sha, sha_lines = generate.verify_inputs()
    check(ok_sha, "输入文件 SHA256 与 input-sha256.json 一致", "; ".join(sha_lines))

    # 3. 离线自足
    external = re.findall(r"""(?:src|href)\s*=\s*["'](https?:)?//[^"']+["']""", html_text)
    check(not external, "无外链资源（script/link/img 等指向 http(s)）", str(external[:5]))
    check("@import" not in html_text, "CSS 无 @import 外部导入")
    remote_css = re.findall(r"url\(\s*['\"]?(https?:)?//[^)]+\)", html_text)
    check(not remote_css, "CSS 无远程 url() 背景/字体", str(remote_css[:5]))
    check("fetch(" not in html_text and "XMLHttpRequest" not in html_text,
          "JS 不发起网络请求（无 fetch / XMLHttpRequest）")

    # 4. 无照片素材
    check("<img" not in html_text.lower(), "无 <img> 图片标签")
    check("<svg" not in html_text.lower(), "无 <svg> 外链图形（插画全部为 CSS 几何）")

    # 5. 六项指标 / 编号 / 数值
    records = generate.read_records()
    ids = [r["id"] for r in records]
    check(len(records) == 6, "CSV 共 6 条指标记录", f"{len(records)} 条")
    missing_ids = [i for i in ids if i not in html_text]
    check(not missing_ids, "6 个资料编号全部出现在 HTML", str(missing_ids))
    missing_ids_md = [i for i in ids if i not in md_text]
    check(not missing_ids_md, "6 个资料编号全部出现在 来源对照.md", str(missing_ids_md))
    for r in records:
        ok = r["name"] in html_text and r["value"] in html_text and r["unit"] in html_text
        check(ok, f"指标「{r['name']}」名称/数值/单位出现在 HTML",
              f"{r['name']}={r['value']}{r['unit']} [{r['id']}]")

    # 6. 三个板块
    for s in generate.SECTIONS:
        check(f'id="panel-{generate.SECTION_SLUG[s]}"' in html_text, f"板块「{s}」面板存在")
        check(f">{s}<" in html_text, f"板块「{s}」标题存在")

    # 7. 虚构声明
    disclaimer, _ = generate.read_note()
    check(disclaimer in html_text, "虚构声明出现在 HTML")
    check(disclaimer in md_text, "虚构声明出现在 来源对照.md")
    decl_pos = html_text.find(disclaimer)
    head_block = re.search(r'<header class="hero">(.*?)</header>', html_text, re.S)
    check(head_block is not None and disclaimer in head_block.group(1),
          "虚构声明位于首屏 hero 区域内（首屏可见）")
    check(decl_pos >= 0, "虚构声明出现在页面中")
    print_block = re.search(r"@media print\s*\{", html_text)
    check(print_block is not None, "存在 @media print 打印样式")
    print_area = html_text[print_block.start():] if print_block else ""
    check(".print-head" in print_area and "display:block" in print_area,
          "打印页输出独立的打印抬头（含声明区域）")
    check('class="print-head"' in html_text, "打印抬头元素存在于正文")
    ph = re.search(r'<div class="print-head">(.*?)</div>', html_text, re.S)
    check(ph is not None and disclaimer in ph.group(1) if ph else False,
          "打印抬头内含虚构声明")

    # 8. JS 失效兜底：静态数值即终值
    nums = re.findall(r'<span class="num"[^>]*data-value="([^"]+)"[^>]*>([^<]*)</span>', html_text)
    check(len(nums) == 6, "页面含 6 个数字节点", f"{len(nums)} 个")
    bad = [(v, t) for v, t in nums if v.strip() != t.strip()]
    check(not bad, "无 JS 时每个数字的静态文本等于其终值（不会恒为 0）", str(bad))
    zeros = [(v, t) for v, t in nums if t.strip() in {"0", "0.0"}]
    check(not zeros, "静态兜底数值中没有 0", str(zeros))

    # 9. 打印规则
    check(".panel{display:block!important" in print_area.replace(" ", ""),
          "打印时展开全部板块")
    check("attr(data-value)" in print_area, "打印时数值由 data-value 强制输出")
    check("beforeprint" in html_text, "打印前事件会把数字收敛到终值")
    check(".summary" in print_area and "table.sum" in print_area, "打印包含总览表")

    # 10. 减弱动效
    check("prefers-reduced-motion: reduce" in html_text, "支持 prefers-reduced-motion")
    check("prefers-reduced-motion" in html_text and "reduced()" in html_text,
          "JS 侧同样尊重 reduced-motion")

    # 11. 控件
    check('id="motion-switch"' in html_text, "存在动画开关")
    check('id="pause-btn"' in html_text, "存在暂停/继续按钮")
    check("暂停动画" in html_text and "继续动画" in html_text, "暂停/继续文案齐备")
    check('id="motion-status"' in html_text, "存在动效状态播报区")

    # 12. 跨单位刻度已移除（订正项）：不得再有进度条 / 刻度百分比 / 满格基准
    check("card__scale" not in html_text, "页面不再输出刻度说明行")
    check(not re.search(r'class="bar"', html_text), "页面不再输出进度条元素")
    check("--fill" not in html_text, "CSS/HTML 不再使用 --fill 刻度变量")
    check(".bar" not in html_text, "样式表不再有 .bar 规则")
    check("刻度" not in html_text, "页面文案不再出现「刻度」")
    check("刻度满格" not in html_text and "跨单位" not in html_text,
          "页面不再出现跨单位刻度/满格对照")
    check("| 刻度 |" not in md_text, "来源对照表不再有刻度列")
    check("30.0%" not in html_text and "42.9%" not in html_text and "90.5%" not in html_text,
          "页面不再出现由跨单位刻度算出的百分比")
    check("刻度" in md_text, "来源对照仍记录了本次订正说明")
    table_cols = re.findall(r"<th scope=\"col\">([^<]+)</th>", html_text)
    check(table_cols == ["板块", "指标", "数值", "单位", "资料编号"],
          "总览表表头为 5 列（无刻度列）", str(table_cols))
    row_cells = re.findall(r"<tr><td>.*?</td></tr>", html_text)
    check(len(row_cells) == 6 and all(r.count("<td") == 5 for r in row_cells),
          "总览表 6 行、每行 5 个单元格", f"{len(row_cells)} 行")
    check("万" in html_text and "百分比" in html_text and "座" in html_text
          and "条" in html_text and "公里" in html_text, "各指标单位仍在页面中原样呈现")

    # 13. 标签闭合
    parser = TagChecker()
    parser.feed(html_text)
    errs = parser.finish()
    check(not errs, "HTML 标签闭合正确", "; ".join(errs[:5]))

    # 14. JS 语法
    script = re.search(r"<script>(.*?)</script>", html_text, re.S)
    if script:
        node = None
        for cand in ("node", "/usr/local/bin/node", "/opt/homebrew/bin/node"):
            try:
                subprocess.run([cand, "-v"], capture_output=True, check=True)
                node = cand
                break
            except Exception:  # noqa: BLE001
                continue
        if node:
            proc = subprocess.run(
                [node, "--check", "-"], input=script.group(1).encode("utf-8"), capture_output=True
            )
            check(proc.returncode == 0, "内联 JS 语法检查通过（node --check）",
                  proc.stderr.decode("utf-8", "replace")[:300])
        else:
            check(True, "内联 JS 语法检查（跳过：未找到 node）")
    else:
        check(False, "找到内联脚本块")

    # 15. 幂等性（内存内重渲染，不写文件）
    disclaimer2, note2 = generate.read_note()
    recs2 = generate.read_records()
    html_again = generate.render_html(recs2, disclaimer2)
    md_again = generate.render_md(recs2, disclaimer2, note2, sha_lines)
    check(html_again == html_text, "重复生成 HTML 逐字节一致（幂等）")
    check(md_again == md_text, "重复生成 Markdown 逐字节一致（幂等）")

    # 16. AI 生成标识
    check('name="generator"' in html_text and "AI" in html_text, "HTML 含 generator AI 标识")
    check('name="ai-generated" content="true"' in html_text, "HTML 含 ai-generated 标识")
    try:
        proc = subprocess.run(["xattr", "-p", "user.ai_generated", str(HTML_PATH)],
                              capture_output=True, text=True, timeout=20)
        check(proc.returncode == 0 and "true" in proc.stdout,
              "HTML 文件属性标记 user.ai_generated=true", proc.stdout.strip() or proc.stderr.strip()[:120])
    except Exception as exc:  # noqa: BLE001
        check(True, f"HTML 文件属性标记（跳过：{exc.__class__.__name__}）")

    report()
    return 0 if all(ok for ok, _, _ in RESULTS) else 1


def report() -> None:
    passed = sum(1 for ok, _, _ in RESULTS if ok)
    total = len(RESULTS)
    print("=" * 74)
    for ok, name, detail in RESULTS:
        mark = "PASS" if ok else "FAIL"
        line = f"[{mark}] {name}"
        if detail and (not ok or name.startswith(("成品", "CSV", "页面含", "6 条刻度", "输入文件", "HTML 文件属性"))):
            line += f"  ({detail})"
        print(line)
    print("=" * 74)
    print(f"结果：{passed}/{total} 项通过")


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