#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""W22 自检脚本：逐项核对内容保留、结构完整、离线性与 375px 约束。
纯标准库，可重复运行：python3 selfcheck.py（结果同时写入 自检结果.txt）。"""

import json
import os
import re
import sys
import xml.etree.ElementTree as ET
from io import StringIO

OUT = os.path.dirname(os.path.abspath(__file__))
SPEC = os.path.join(OUT, "..", "inputs", "spec.json")

results = []
passed = 0
failed = 0


def check(name, ok, detail=""):
    global passed, failed
    status = "PASS" if ok else "FAIL"
    if ok:
        passed += 1
    else:
        failed += 1
    results.append(f"[{status}] {name}" + (f" —— {detail}" if detail else ""))


def read(path):
    with open(path, encoding="utf-8") as f:
        return f.read()


# ---------- 1. 源文一致性：article.md 与 spec.json 逐字一致 ----------
spec = json.loads(read(SPEC))
md_src = spec["articleMarkdown"]
md_out = read(os.path.join(OUT, "article.md"))
check("1. article.md 与 spec.json 的 articleMarkdown 逐字一致",
      md_out.strip() == md_src.strip(),
      f"源 {len(md_src.strip())} 字符 / 产出 {len(md_out.strip())} 字符")

html = read(os.path.join(OUT, "article.html"))

# ---------- 2. 内容保留：逐项检索源文文本单元 ----------
md_items = [
    ("2.1 一级标题", "把周五晚上的空闲，留给一盏灯"),
    ("2.2 段落正文", "这是一篇原创排版练习。我们用一个晚上，把桌面整理得更舒服。"),
    ("2.3 二级标题一", "先留一块空白"),
    ("2.4 引用块", "收纳不是把所有东西藏起来，而是让常用的东西找得到。"),
    ("2.5 有序列表项1", "清出一块放笔记本的区域。"),
    ("2.6 有序列表项2", "把充电线收在桌边。"),
    ("2.7 有序列表项3", "留一盏亮度合适的灯。"),
    ("2.8 图片替代文字", "台灯与桌面的抽象示意图"),
    ("2.9 二级标题二", "记下一个小动作"),
    ("2.10 代码块行1", "今天完成：整理桌面"),
    ("2.11 代码块行2", "下次开始：读三页书"),
    ("2.12 链接文字", "Markdown说明"),
    ("2.13 链接地址", "https://commonmark.org/help/"),
    ("2.14 表头-物品", "物品"),
    ("2.15 表头-数量", "数量"),
    ("2.16 表体行1", "笔记本"),
    ("2.17 表体行2", "台灯"),
    ("2.18 结尾加粗句", "这个周五，不赶进度。"),
    ("2.19 作者", "赛博游园会练习编辑"),
    ("2.20 日期", "2026-11-27"),
]
for name, text in md_items:
    check(name, text in html, f"「{text}」")

# ---------- 3. HTML 结构元素 ----------
struct_items = [
    ("3.1 标题元素 h1×2（页头+正文）", html.count("<h1") >= 2),
    ("3.2 二级标题 h2×2", html.count("<h2") == 2),
    ("3.3 引用块 blockquote", "<blockquote>" in html),
    ("3.4 有序列表 ol 且含 3 个 li",
     "<ol>" in html and html.count("<li>") >= 3),
    ("3.5 图片 img 带 alt",
     re.search(r'<img[^>]+alt="台灯与桌面的抽象示意图"', html) is not None),
    ("3.6 图注 figcaption 可见展示替代文字",
     "<figcaption>台灯与桌面的抽象示意图</figcaption>" in html),
    ("3.7 代码块 pre/code",
     "<pre><code>" in html and "</code></pre>" in html),
    ("3.8 链接 a[href=https://commonmark.org/help/]",
     'href="https://commonmark.org/help/"' in html),
    ("3.9 表格 table/thead/tbody",
     "<table>" in html and "<thead>" in html and "<tbody>" in html),
    ("3.10 加粗 strong 结尾句",
     "<strong>这个周五，不赶进度。</strong>" in html),
]
for name, ok in struct_items:
    check(name, ok)

# ---------- 4. lamp.svg：程序绘制、XML 合法、原创图形 ----------
svg_path = os.path.join(OUT, "lamp.svg")
try:
    svg_txt = read(svg_path)
    ET.fromstring(svg_txt)
    n_shapes = sum(svg_txt.count(t) for t in ("<rect", "<circle", "<ellipse", "<polygon", "<polyline"))
    check("4.1 lamp.svg 为合法 XML 且包含 ≥10 个绘制图元", n_shapes >= 10, f"{n_shapes} 个图元")
    check("4.2 lamp.svg 含可访问性 aria-label", 'aria-label="台灯与桌面的抽象示意图"' in svg_txt)
    check("4.3 lamp.svg 无外部引用（无 http/src/image）",
          "http" not in svg_txt.replace('xmlns="http://www.w3.org/2000/svg"', "") and "<image" not in svg_txt)
except Exception as e:
    check("4. lamp.svg 解析", False, str(e))

# ---------- 5. 离线性：HTML 无外部资源依赖 ----------
remote = re.findall(r'(?:src|href)="(https?://[^"]+)"', html)
remote_res = [u for u in remote if not u.startswith("https://commonmark.org")]  # 正文链接属内容而非资源
check("5.1 HTML 无外部资源（CDN/网络字体/远程图片），仅保留正文内容链接",
      len(remote_res) == 0, f"非内容外链 {remote_res}")
css = read(os.path.join(OUT, "style.css"))
check("5.2 style.css 无 @import/url() 外部引用",
      not re.search(r'@import|url\(\s*[\'"]?https?:', css))
check("5.3 HTML 引用本地样式 style.css", 'href="style.css"' in html)
check("5.4 HTML 引用本地图片 lamp.svg", 'src="lamp.svg"' in html)
check("5.5 无 <script src> 外部脚本（复制逻辑为内联本地脚本）",
      '<script src' not in html)

# ---------- 6. 375px 适配：静态约束核对 ----------
check("6.1 视口 meta viewport 存在",
      'content="width=device-width, initial-scale=1.0"' in html)
check("6.2 代码块局部横向滚动 pre{overflow-x:auto}",
      re.search(r'\.article pre\s*{[^}]*overflow-x:\s*auto', css, re.S) is not None)
check("6.3 表格容器局部滚动 .table-wrap{overflow-x:auto}",
      re.search(r'\.table-wrap\s*{[^}]*overflow-x:\s*auto', css, re.S) is not None)
check("6.4 图片 max-width:100% 不超容器",
      re.search(r'\.article figure img\s*{[^}]*max-width:\s*100%', css, re.S) is not None)
check("6.5 body overflow-x:hidden 兜底",
      re.search(r'body\s*{[^}]*overflow-x:\s*hidden', css, re.S) is not None)
check("6.6 针对 ≤375px 的媒体查询存在",
      "@media (max-width: 375px)" in css)
check("6.7 img 固定宽高不超过 375px 可视范围（HTML width=640 但 CSS 已限制 100%）",
      'width="640"' in html and "max-width: 100%" in css)
check("6.8 长链接 word-break:break-all",
      "word-break: break-all" in css)

# ---------- 7. 复制正文按钮与失败提示 ----------
check("7.1 复制按钮存在（btn-copy）", 'id="btn-copy"' in html)
check("7.2 复制范围为正文容器 article-body", 'id="article-body"' in html)
check("7.3 Clipboard API + execCommand 双通道", "navigator.clipboard" in html and "execCommand" in html)
check("7.4 复制失败提示框（copy-fail）存在且含可操作建议",
      'id="copy-fail"' in html and "长按正文区域" in html and "允许「复制到剪贴板」" in html)

# ---------- 8. 合规与界面 ----------
check("8.1 页脚声明未发送草稿/未连接账号/未发布",
      "未发送公众号草稿" in html and "未连接任何发布账号" in html and "未发布" in html)
check("8.2 页面 lang=zh-CN（中文界面）", '<html lang="zh-CN">' in html)
check("8.3 无账号/登录要求字样", not re.search(r"登录|注册|扫码|授权公众号", html))

# ---------- 9. 交付包文件齐全 ----------
required = ["article.html", "article.md", "style.css", "lamp.svg", "gen_lamp.py",
            "内容对照表.md", "README.md", "selfcheck.py", "自检结果.txt"]
missing = [f for f in required if f != "自检结果.txt" and not os.path.exists(os.path.join(OUT, f))]
check("9.1 交付包文件齐全（自检结果.txt 由本次运行生成）",
      not missing,
      f"缺失 {missing}" if missing else "9 个文件")

# ---------- 输出 ----------
report_lines = [
    "=" * 62,
    "W22 自检结果（selfcheck.py 实际运行输出）",
    f"运行目录: {OUT}",
    f"项目: 赛博游园会合成练习 W22 —— 公众号本地排版",
    "=" * 62,
    *results,
    "-" * 62,
    f"合计: {passed + failed} 项 | 通过 {passed} | 失败 {failed}",
    "=" * 62,
]
report = "\n".join(report_lines)
print(report)
with open(os.path.join(OUT, "自检结果.txt"), "w", encoding="utf-8") as f:
    f.write(report + "\n")
sys.exit(0 if failed == 0 else 1)
