#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Static and data-integrity checks for the built D07 HTML.

This test is deliberately independent from the build script's graph checker:
it re-parses the generated HTML, compares the embedded story with the read-only
input, walks every start-to-ending path, and checks the offline/UI/save contract.
"""

from __future__ import annotations

import json
import re
import sys
from collections import deque
from html.parser import HTMLParser
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
INPUT_STORY = ROOT.parent / "inputs" / "原创剧情.json"
HTML_FILE = ROOT / "灯塔故事.html"
ENGINE_FILE = ROOT / "src" / "engine.js"
SAVE_FILE = ROOT / "src" / "save.js"

EXPECTED_ENDINGS = {"归航", "守望", "真相"}
VOID_TAGS = {
    "area", "base", "br", "col", "embed", "hr", "img", "input", "link",
    "meta", "param", "source", "track", "wbr",
}
REQUIRED_IDS = {
    "app", "story-panel", "location-chip", "location-name", "step-label",
    "narration", "scene-title", "scene-ambient", "choices", "ending-block",
    "ending-name", "ending-text", "ending-code", "ending-note", "ending-undo",
    "ending-restart", "collection-panel", "collection-count",
    "collection-count-top", "collection-bar", "ending-list", "collection-note",
    "path-list", "undo", "restart", "clear", "save-status",
    "save-status-text", "notice", "notice-text", "notice-close", "clear-modal",
    "clear-count", "clear-step", "clear-cancel", "clear-confirm", "toast",
    "sr-status", "story-data", "display-data",
}

PASSED = 0
FAILURES: list[str] = []


def check(name: str, condition: bool, detail: str = "") -> None:
    global PASSED
    if condition:
        PASSED += 1
        print(f"ok {PASSED} - {name}")
    else:
        FAILURES.append(name + (f": {detail}" if detail else ""))
        print(f"not ok - {name}" + (f": {detail}" if detail else ""))


class DocumentParser(HTMLParser):
    def __init__(self) -> None:
        super().__init__(convert_charrefs=False)
        self.stack: list[tuple[str, int]] = []
        self.errors: list[str] = []
        self.ids: list[str] = []
        self.roles: list[tuple[str, int]] = []
        self.tags: list[tuple[str, int]] = []
        self.attrs_by_id: dict[str, dict[str, str]] = {}

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        line = self.getpos()[0]
        attr_map = {key: (value if value is not None else "") for key, value in attrs}
        self.tags.append((tag, line))
        if "id" in attr_map:
            self.ids.append(attr_map["id"])
            self.attrs_by_id[attr_map["id"]] = attr_map
        if "role" in attr_map:
            self.roles.append((attr_map["role"], line))
        if tag not in VOID_TAGS:
            self.stack.append((tag, line))

    def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        line = self.getpos()[0]
        attr_map = {key: (value if value is not None else "") for key, value in attrs}
        self.tags.append((tag, line))
        if "id" in attr_map:
            self.ids.append(attr_map["id"])
            self.attrs_by_id[attr_map["id"]] = attr_map
        if "role" in attr_map:
            self.roles.append((attr_map["role"], line))

    def handle_endtag(self, tag: str) -> None:
        line = self.getpos()[0]
        if tag in VOID_TAGS:
            return
        if not self.stack:
            self.errors.append(f"line {line}: unexpected </{tag}>")
            return
        open_tag, open_line = self.stack.pop()
        if open_tag != tag:
            self.errors.append(
                f"line {line}: </{tag}> closes <{open_tag}> opened at line {open_line}"
            )


def extract_json_script(html: str, element_id: str) -> object:
    pattern = re.compile(
        r'<script\b[^>]*\bid="' + re.escape(element_id) + r'"[^>]*>(.*?)</script>',
        re.S,
    )
    match = pattern.search(html)
    if not match:
        raise AssertionError(f"missing JSON script #{element_id}")
    return json.loads(match.group(1))


def enumerate_paths(nodes: dict, start: str) -> list[list[str]]:
    paths: list[list[str]] = []

    def walk(node_id: str, path: list[str]) -> None:
        node = nodes[node_id]
        if "ending" in node:
            paths.append(path.copy())
            return
        for choice in node.get("choices", []):
            target = choice["next"]
            if target in path:
                continue
            path.append(target)
            walk(target, path)
            path.pop()

    walk(start, [start])
    return paths


def main() -> int:
    check("built HTML exists", HTML_FILE.is_file(), str(HTML_FILE))
    if not HTML_FILE.is_file():
        return 1

    raw = HTML_FILE.read_bytes()
    check("built HTML is valid UTF-8", raw.decode("utf-8") is not None)
    html = raw.decode("utf-8")
    check("no UTF-8 BOM", not raw.startswith(b"\xef\xbb\xbf"))
    check("doctype and lang", html.lstrip().lower().startswith("<!doctype html>") and 'lang="zh-CN"' in html)
    check("AI marker comment present", "AI 生成标识" in html)
    check("single-file size is plausible", len(raw) > 40_000, f"{len(raw)} bytes")

    input_story = json.loads(INPUT_STORY.read_text(encoding="utf-8"))
    story = extract_json_script(html, "story-data")
    display = extract_json_script(html, "display-data")

    check("embedded story equals read-only input exactly", story == input_story)
    check("story title preserved", story.get("title") == "灯塔最后一封信")
    check("display metadata covers every node", set(display) == set(story["nodes"]))

    nodes = story["nodes"]
    start = story["start"]
    check("start node exists", start in nodes)

    endings: dict[str, str] = {}
    invalid_nodes: list[str] = []
    for node_id, node in nodes.items():
        if not isinstance(node.get("text"), str) or not node["text"].strip():
            invalid_nodes.append(f"{node_id}:text")
        if "ending" in node:
            endings[node["ending"]] = node_id
            if node.get("choices"):
                invalid_nodes.append(f"{node_id}:ending-with-choices")
        else:
            if not node.get("choices"):
                invalid_nodes.append(f"{node_id}:no-choices")
            for choice in node.get("choices", []):
                if not choice.get("label") or choice.get("next") not in nodes:
                    invalid_nodes.append(f"{node_id}:bad-choice")
    check("all nodes have valid text/choices/endings", not invalid_nodes, ", ".join(invalid_nodes))
    check("exactly three endings", len(endings) == 3, f"got {len(endings)}")
    check("ending names match original story", set(endings) == EXPECTED_ENDINGS, str(sorted(endings)))
    check("ending nodes are unique", len(set(endings.values())) == len(endings))

    adjacency = {
        node_id: [choice["next"] for choice in node.get("choices", [])]
        for node_id, node in nodes.items()
    }
    reachable: set[str] = set()
    queue = deque([start])
    while queue:
        current = queue.popleft()
        if current in reachable:
            continue
        reachable.add(current)
        queue.extend(adjacency[current])
    check("all nodes reachable from start", reachable == set(nodes), str(sorted(set(nodes) - reachable)))

    reverse: dict[str, list[str]] = {node_id: [] for node_id in nodes}
    for source, targets in adjacency.items():
        for target in targets:
            reverse[target].append(source)
    can_finish = set(endings.values())
    queue = deque(endings.values())
    while queue:
        current = queue.popleft()
        for predecessor in reverse[current]:
            if predecessor not in can_finish:
                can_finish.add(predecessor)
                queue.append(predecessor)
    check("no node is a dead end", can_finish == set(nodes), str(sorted(set(nodes) - can_finish)))

    paths = enumerate_paths(nodes, start)
    path_endings = {nodes[path[-1]]["ending"] for path in paths}
    check("all branches resolve to endings", len(paths) >= 6, f"paths={len(paths)}")
    check("all three endings are reachable", path_endings == EXPECTED_ENDINGS, str(sorted(path_endings)))

    used_edges: set[tuple[str, str]] = set()
    for path in paths:
        for source, target in zip(path, path[1:]):
            used_edges.add((source, target))
    all_edges = {
        (source, target)
        for source, targets in adjacency.items()
        for target in targets
    }
    check("every choice edge lies on a start-to-ending path", used_edges == all_edges,
          f"missing={sorted(all_edges - used_edges)}")

    parser = DocumentParser()
    parser.feed(html)
    parser.close()
    check("HTML tags balance", not parser.errors, "; ".join(parser.errors[:5]))
    check("no duplicate element ids", len(parser.ids) == len(set(parser.ids)),
          str([item for item in parser.ids if parser.ids.count(item) > 1]))
    missing_ids = sorted(REQUIRED_IDS - set(parser.ids))
    check("required UI ids present", not missing_ids, str(missing_ids))
    roles = {role for role, _ in parser.roles}
    check("progressbar and dialog roles present", {"progressbar", "dialog"}.issubset(roles), str(roles))

    modal_attrs = parser.attrs_by_id.get("clear-modal", {})
    check("clear modal starts hidden", "hidden" in modal_attrs)
    check(
        "clear modal is a labelled dialog",
        'role="dialog"' in html
        and 'aria-modal="true"' in html
        and 'aria-labelledby="clear-title"' in html,
    )
    check("ending block starts hidden", "hidden" in parser.attrs_by_id.get("ending-block", {}))
    check("notice starts hidden", "hidden" in parser.attrs_by_id.get("notice", {}))
    check("story JSON is embedded", 'id="story-data"' in html)
    check("display JSON is embedded", 'id="display-data"' in html)

    required_text = [
        "当前位置", "结局收集", "结局档案", "返回上一步", "从头开始",
        "清空存档", "确认清空", "取消", "已自动存档", "离线单文件",
    ]
    missing_text = [text for text in required_text if text not in html]
    check("required Chinese UI copy present", not missing_text, str(missing_text))
    check("three save-action texts present",
          all(text in html for text in ("返回上一步", "从头开始", "清空存档")))
    check("double-confirm copy present", "需要二次确认" in html and "确认清空" in html)
    check("ending collection copy present", "0 / 3" in html and "aria-valuemax=\"3\"" in html)

    check("meta save key present", 'name="d07:save-key" content="cyberfete.d07.lighthouse.save"' in html)
    check("meta schema present", 'name="d07:schema" content="cyberfete.d07.lighthouse"' in html)
    check("meta save version present", 'name="d07:save-version" content="1"' in html)
    check("localStorage used", "window.localStorage" in html)
    check("save validation wired", "validateSave" in html and "removeItem" in html)
    check("undo/restart/clear handlers wired",
          all(needle in html for needle in ("handleUndo", "handleRestart", "handleClearConfirm")))
    check("clear confirmation modal opens before deletion",
          "openClearModal" in html and "clearConfirm.addEventListener" in html)

    engine_source = ENGINE_FILE.read_text(encoding="utf-8")
    save_source = SAVE_FILE.read_text(encoding="utf-8")
    check("engine save schema constant", 'cyberfete.d07.lighthouse' in engine_source)
    check("engine save version constant", "SAVE_VERSION = 1" in engine_source)
    check("engine and storage share key", "cyberfete.d07.lighthouse.save" in engine_source and
          "cyberfete.d07.lighthouse.save" in save_source)
    check("old-version reason exists", '"version"' in engine_source)
    check("corrupt-json reason exists", '"json"' in engine_source)
    check("save manager handles unavailable storage", "unavailable" in save_source and
          "storage-error" in save_source)

    lowered = html.lower()
    network_patterns = {
        "http(s) URL": r"https?://",
        "external script src": r"<script[^>]*\bsrc\s*=",
        "link element": r"<link\b",
        "CSS import": r"@import",
        "external CSS url()": r"url\s*\(\s*['\"]?(?:https?:)?//",
        "fetch": r"\bfetch\s*\(",
        "XMLHttpRequest": r"xmlhttprequest",
        "WebSocket": r"websocket",
        "EventSource": r"eventsource",
        "sendBeacon": r"sendbeacon",
        "iframe/object/embed": r"<(?:iframe|object|embed)\b",
        "font-face": r"@font-face",
    }
    for label, pattern in network_patterns.items():
        found = re.search(pattern, lowered)
        check(f"no {label}", found is None, found.group(0) if found else "")
    check("no external img", "<img" not in lowered)
    check("no remote form action", "action=\"http" not in lowered)
    check("inline style and scripts only",
          html.count("<style") == 1 and html.count("<script") == 5,
          f"style={html.count('<style')}, script={html.count('<script')}")

    if FAILURES:
        print(f"\n{len(FAILURES)} check(s) failed, {PASSED} passed.")
        for failure in FAILURES:
            print(f"  FAIL: {failure}")
        return 1

    print(f"\n{PASSED} checks passed.")
    print("branch witnesses:")
    for ending_name, ending_id in sorted(endings.items()):
        for path in paths:
            if path[-1] == ending_id:
                print(f"  {ending_name}: {' -> '.join(path)}")
                break
    return 0


if __name__ == "__main__":
    sys.exit(main())
