#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Build the offline single-file game for D07.

Reads the read-only original story from ../inputs/原创剧情.json, merges the
presentational location copy from src/display.json, and inlines the CSS, game
engine, save manager and UI into one HTML file. No network resources are used.

Usage:
    python3 build_game.py
    python3 build_game.py --check-only
"""

from __future__ import annotations

import argparse
import hashlib
import json
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent
INPUT_STORY = ROOT.parent / "inputs" / "原创剧情.json"
SRC = ROOT / "src"
OUTPUT = ROOT / "灯塔故事.html"
EXPECTED_ENDINGS = {"归航", "守望", "真相"}
ALLOWED_TONES = {"fog", "sea", "lamp", "archive"}


def read_text(path: Path) -> str:
    return path.read_text(encoding="utf-8")


def load_json(path: Path) -> object:
    with path.open("r", encoding="utf-8") as handle:
        return json.load(handle)


def graph_check(story: dict) -> dict:
    if not isinstance(story, dict):
        raise ValueError("剧情根节点必须是对象")
    if not isinstance(story.get("title"), str) or not story["title"].strip():
        raise ValueError("剧情缺少 title")
    if not isinstance(story.get("nodes"), dict) or not story["nodes"]:
        raise ValueError("剧情缺少 nodes")
    if not isinstance(story.get("start"), str):
        raise ValueError("剧情缺少 start")

    nodes = story["nodes"]
    start = story["start"]
    if start not in nodes:
        raise ValueError(f"start 指向不存在的节点：{start}")

    endings: dict[str, str] = {}
    for node_id, node in nodes.items():
        if not isinstance(node_id, str) or not node_id:
            raise ValueError("节点 id 必须是非空字符串")
        if not isinstance(node, dict):
            raise ValueError(f"节点 {node_id} 必须是对象")
        if not isinstance(node.get("text"), str) or not node["text"].strip():
            raise ValueError(f"节点 {node_id} 缺少 text")
        if "ending" in node:
            ending = node["ending"]
            if not isinstance(ending, str) or not ending.strip():
                raise ValueError(f"节点 {node_id} 的 ending 无效")
            if ending in endings:
                raise ValueError(f"结局名称重复：{ending}")
            endings[ending] = node_id
            if node.get("choices"):
                raise ValueError(f"结局节点 {node_id} 不应再有 choices")
        else:
            choices = node.get("choices")
            if not isinstance(choices, list) or not choices:
                raise ValueError(f"非结局节点 {node_id} 缺少 choices")
            for choice in choices:
                if not isinstance(choice, dict):
                    raise ValueError(f"节点 {node_id} 存在无效 choice")
                if not isinstance(choice.get("label"), str) or not choice["label"].strip():
                    raise ValueError(f"节点 {node_id} 存在空 choice label")
                target = choice.get("next")
                if not isinstance(target, str) or target not in nodes:
                    raise ValueError(f"节点 {node_id} 的 choice 指向不存在节点：{target}")

    if len(endings) != 3:
        raise ValueError(f"必须且只能有 3 个结局，实际 {len(endings)} 个")
    if set(endings) != EXPECTED_ENDINGS:
        raise ValueError(
            "结局集合与原始剧情不一致："
            + ", ".join(sorted(endings))
            + "；期望："
            + ", ".join(sorted(EXPECTED_ENDINGS))
        )

    adjacency = {
        node_id: [choice["next"] for choice in node.get("choices", [])]
        for node_id, node in nodes.items()
    }

    reachable: set[str] = set()
    frontier = [start]
    while frontier:
        current = frontier.pop()
        if current in reachable:
            continue
        reachable.add(current)
        frontier.extend(adjacency[current])

    unreachable = sorted(set(nodes) - reachable)
    if unreachable:
        raise ValueError("存在从起点不可达的节点：" + ", ".join(unreachable))

    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_reach_ending: set[str] = set(endings.values())
    frontier = list(endings.values())
    while frontier:
        current = frontier.pop()
        for predecessor in reverse[current]:
            if predecessor not in can_reach_ending:
                can_reach_ending.add(predecessor)
                frontier.append(predecessor)

    dead_ends = sorted(set(nodes) - can_reach_ending)
    if dead_ends:
        raise ValueError("存在无法抵达任何结局的节点：" + ", ".join(dead_ends))

    witnesses: dict[str, list[str]] = {}
    for ending_name, ending_id in endings.items():
        stack: list[tuple[str, list[str]]] = [(start, [start])]
        found: list[str] | None = None
        while stack:
            current, path = stack.pop()
            if current == ending_id:
                found = path
                break
            for target in reversed(adjacency[current]):
                if target not in path:
                    stack.append((target, path + [target]))
        if found is None:
            raise ValueError(f"结局 {ending_name} 从起点不可达")
        witnesses[ending_name] = found

    return {
        "nodes": len(nodes),
        "endings": endings,
        "witnesses": witnesses,
        "reachable": len(reachable),
    }


def validate_display(display: object, story: dict) -> None:
    if not isinstance(display, dict):
        raise ValueError("display.json 必须是对象")
    if set(display) != set(story["nodes"]):
        missing = sorted(set(story["nodes"]) - set(display))
        extra = sorted(set(display) - set(story["nodes"]))
        raise ValueError(f"display.json 节点不一致；缺少 {missing}，多余 {extra}")
    for node_id, meta in display.items():
        if not isinstance(meta, dict):
            raise ValueError(f"display.{node_id} 必须是对象")
        for key in ("place", "eyebrow", "ambient"):
            if not isinstance(meta.get(key), str) or not meta[key].strip():
                raise ValueError(f"display.{node_id}.{key} 无效")
        if meta.get("tone") not in ALLOWED_TONES:
            raise ValueError(f"display.{node_id}.tone 无效：{meta.get('tone')}")


def inline_json(value: object) -> str:
    encoded = json.dumps(value, ensure_ascii=False, indent=2)
    return encoded.replace("</", "<\\/")


def inline_placeholder(template: str, marker: str, content: str, label: str) -> str:
    count = template.count(marker)
    if count != 1:
        raise ValueError(f"模板占位符 {label} 应出现 1 次，实际 {count} 次")
    return template.replace(marker, content)


def static_guard(html: str) -> None:
    lowered = html.lower()
    forbidden = {
        "http://": "http://",
        "https://": "https://",
        "<script src": "<script src",
        "<link": "<link",
        "@import": "@import",
        "url(http": "url(http",
        "url(//": "url(//",
        'url("http': 'url("http',
        "url('http": "url('http",
        "fetch(": "fetch(",
        "xmlhttprequest": "XMLHttpRequest",
        "websocket": "WebSocket",
        "eventsource": "EventSource",
    }
    for needle, label in forbidden.items():
        if needle in lowered:
            raise ValueError(f"产物包含不允许的网络/外部资源标记：{label}")


def mark_ai_generated(path: Path) -> None:
    """Best-effort macOS extended attribute marker. Never fatal."""
    try:
        subprocess.run(
            ["xattr", "-w", "com.dsh.ai-generated", "D07 · AI生成 · DeepSeek Harness", str(path)],
            check=False,
            capture_output=True,
        )
        subprocess.run(
            ["xattr", "-w", "user.aigenerated", "true", str(path)],
            check=False,
            capture_output=True,
        )
    except OSError:
        pass


def main() -> int:
    parser = argparse.ArgumentParser(description="构建 D07 离线互动游戏")
    parser.add_argument("--check-only", action="store_true", help="只校验输入与源文件，不写 HTML")
    parser.add_argument("--output", type=Path, default=OUTPUT, help="输出 HTML 路径")
    args = parser.parse_args()

    story = load_json(INPUT_STORY)
    display = load_json(SRC / "display.json")
    if not isinstance(story, dict):
        raise ValueError("原创剧情必须是 JSON 对象")

    graph = graph_check(story)
    validate_display(display, story)

    template = read_text(SRC / "template.html")
    styles = read_text(SRC / "styles.css")
    engine = read_text(SRC / "engine.js")
    save = read_text(SRC / "save.js")
    app = read_text(SRC / "app.js")

    for label, source in (("engine.js", engine), ("save.js", save), ("app.js", app)):
        if "</script" in source.lower():
            raise ValueError(f"{label} 包含 </script，不能安全内联")

    html = inline_placeholder(template, "/*__STYLES__*/", styles, "styles")
    html = inline_placeholder(html, "/*__STORY_DATA__*/", inline_json(story), "story")
    html = inline_placeholder(html, "/*__DISPLAY_DATA__*/", inline_json(display), "display")
    html = inline_placeholder(html, "/*__ENGINE__*/", engine, "engine")
    html = inline_placeholder(html, "/*__SAVE__*/", save, "save")
    html = inline_placeholder(html, "/*__APP__*/", app, "app")

    header = (
        "<!--\n"
        "  灯塔最后一封信 · 离线互动故事\n"
        "  生成脚本：build_game.py（可重复运行）\n"
        "  数据源：../inputs/原创剧情.json（只读）\n"
        "  本文件不含网络资源；AI 生成标识见扩展属性。\n"
        "-->\n"
    )
    html = html.replace("<!doctype html>", "<!doctype html>\n" + header, 1)

    static_guard(html)

    if not args.check_only:
        args.output.write_text(html, encoding="utf-8", newline="\n")
        mark_ai_generated(args.output)

    digest = hashlib.sha256(html.encode("utf-8")).hexdigest()
    print(f"story: {story['title']}")
    print(f"nodes: {graph['nodes']} | reachable: {graph['reachable']} | endings: {len(graph['endings'])}")
    for name, path in graph["witnesses"].items():
        print(f"  {name}: {' -> '.join(path)}")
    print(f"bytes: {len(html.encode('utf-8'))}")
    print(f"sha256: {digest}")
    if args.check_only:
        print("check-only: OK (no file written)")
    else:
        print(f"wrote: {args.output}")
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception as exc:  # pragma: no cover - CLI feedback
        print(f"BUILD FAILED: {exc}", file=sys.stderr)
        sys.exit(1)
