#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
W31 自检脚本（可重复使用）：对 outputs/ 内三个成品做实际检查，
并把真实检查结果写入 自检报告.md。不操作浏览器。
用法: python3 verify_faq.py
"""
import csv
import json
import os
import re
import sys

BASE = os.path.dirname(os.path.abspath(__file__))
SPEC_PATH = os.path.join(BASE, "..", "inputs", "spec.json")

with open(SPEC_PATH, "r", encoding="utf-8") as f:
    spec = json.load(f)
docs = {d["id"]: d["text"] for d in spec["documents"]}

results = []  # (检查项, 通过?, 详情)

def check(name, ok, detail):
    results.append((name, ok, detail))

html = open(os.path.join(BASE, "FAQ.html"), encoding="utf-8").read()
md = open(os.path.join(BASE, "FAQ.md"), encoding="utf-8").read()
with open(os.path.join(BASE, "FAQ.csv"), encoding="utf-8-sig", newline="") as f:
    rows = list(csv.reader(f))

# 1. CSV 行数与表头
check("FAQ.csv 含表头+5行数据", len(rows) == 6, "实际数据行 %d" % (len(rows) - 1))

# 2. 五问逐条引用与原文逐字一致
quotes = [
    ("P2026", "普通差旅住宿上限每晚350元。"),
    ("P2025", "普通差旅住宿上限每晚300元。"),
    ("P2026", "特殊活动经事前书面批准可超过住宿上限。"),
    ("P2026", "须在返回后10日内提交报销。"),
]
ok = all(q in docs[d] for d, q in quotes)
check("4条有依据答案的引用均为原文逐字子串", ok,
      "逐条比对 inputs/spec.json 原文通过" if ok else "存在不一致")

# 3. 例外条件未丢失
exc_ok = ("特殊活动" in html and "事前书面批准" in html and "两个条件缺一不可" in html
          and "事前书面批准" in md and "事前书面批准" in "".join(rows[3]))
check("例外条件（特殊活动+事前书面批准）在HTML/MD/CSV中完整保留", exc_ok, "三处成品均含例外条件")

# 4. 餐饮未知声明
meal_ok = ("未知" in html and "无依据" in html and "餐饮" in html
           and "否（未知）" in "".join(rows[5]))
no_meal_basis = all("餐" not in t for t in docs.values())
check("第5问餐饮明确标注未知/无依据，且材料中确实无餐饮条款",
      meal_ok and no_meal_basis,
      "材料含“餐”字样: %s" % [d for d, t in docs.items() if "餐" in t] if not no_meal_basis else "三份原文均无“餐”字")

# 5. 新旧冲突明确指出
conf_ok = ("每晚300元" in html and "每晚350元" in html and "未随2026制度更新" in html
           and "冲突" in md and "未随2026制度更新" in md)
check("新旧FAQ/新旧制度冲突已明确指出", conf_ok, "HTML与MD均含冲突章节及旧FAQ原文提示")

# 6. HTML 锚点完整（出处可点击跳转）
hrefs = set(re.findall(r'href="#([^"]+)"', html))
ids = set(re.findall(r'id="([^"]+)"', html))
check("HTML 内部链接均有对应锚点（出处可跳原文段落）", hrefs <= ids,
      "链接 %d 个，缺失目标: %s" % (len(hrefs), hrefs - ids) if hrefs - ids else "P2025/P2026/FAQ 原文段落锚点齐全")

# 7. 离线可用：无外部资源引用
ext = re.findall(r'(?:src|href)="https?://[^"]+"', html) + re.findall(r'url\(\s*[\'"]?https?://', html)
check("HTML 无外部 http(s) 资源（可离线打开，不依赖CDN）", not ext,
      "外部引用: %s" % ext if ext else "样式内联、无外链字体/脚本")

# 8. 手机适配
check("HTML 含 viewport 与移动端媒体查询", "width=device-width" in html and "max-width:600px" in html,
      "meta viewport + @media 断点均存在")

# 9. 合成数据声明
disc_ok = "合成练习数据" in html and "不代表任何真实公司制度" in html and "合成练习数据" in md
check("已声明为合成练习数据、未冒充真实公司制度", disc_ok, "HTML顶部声明条 + MD声明均在")

# 10. 按年份适用
year_ok = ("2025" in html and "2026" in html and "按问题所涉年份" in html)
check("答案按问题年份适用对应制度版本", year_ok, "HTML说明与各答案均标注适用年份/制度")

# 11. 空值/错误提示
empty_ok = "（无——材料中无相关原句）" in "".join(rows[5]) and "未知" in rows[5][9]
check("空值以显式提示呈现（无引用时标注“无相关原句”、依据列为“否（未知）”）",
      empty_ok, "CSV第5行空字段均有占位说明")

# ---------- 写自检报告 ----------
passed = sum(1 for _, ok, _ in results if ok)
total = len(results)
lines = [
    "# W31 自检报告（实际执行结果）",
    "",
    "- 执行时间脚本：`verify_faq.py`（可重复运行）",
    "- 被检文件：outputs/FAQ.html、outputs/FAQ.csv、outputs/FAQ.md",
    "- 结论：**%d / %d 项通过**" % (passed, total),
    "",
    "| # | 检查项 | 结果 | 详情 |",
    "|---|--------|------|------|",
]
for i, (name, ok, detail) in enumerate(results, 1):
    lines.append("| %d | %s | %s | %s |" % (i, name, "✅ 通过" if ok else "❌ 未通过", detail))
lines += [
    "",
    "## 说明",
    "",
    "- 本报告由校验脚本对成品文件**实际读取比对**后生成，非人工估填；如需复核可再次运行 `python3 verify_faq.py`。",
    "- 输入文件 inputs/spec.json 全程只读，未修改、未删除任何文件。",
    "- 本题全部材料为合成练习数据（虚构制度），不代表任何真实公司制度。",
]
with open(os.path.join(BASE, "自检报告.md"), "w", encoding="utf-8") as f:
    f.write("\n".join(lines))

for name, ok, detail in results:
    print(("PASS" if ok else "FAIL"), name, "--", detail)
print("自检报告已写入：", os.path.join(BASE, "自检报告.md"))
sys.exit(0 if passed == total else 1)
