"""Scene graph validation: ``spec/scene.schema.json`` + compiler checks (TZ 2.3, 2.4.3 p.4)."""

from __future__ import annotations

import json
from functools import lru_cache
from typing import Any

from django.conf import settings
from jsonschema import Draft202012Validator

from snapfile.core.errors import ApiError
from snapfile_render.compiler import compile_document
from snapfile_render.errors import RenderError
from snapfile_render.expr.parser import collect_paths

MAX_ERRORS = 100


@lru_cache(maxsize=1)
def scene_validator() -> Draft202012Validator:
    schema = json.loads((settings.SNAPFILE_SPEC_DIR / "scene.schema.json").read_text(encoding="utf-8"))
    return Draft202012Validator(schema)


def _pointer(path: Any) -> str:
    return "/" + "/".join(str(p) for p in path)


def _broken_expressions(doc: dict[str, Any]) -> list[dict[str, Any]]:
    """A ``{{`` without ``}}`` inside one run means the editor split an expression between runs."""
    out: list[dict[str, Any]] = []

    def walk(nodes: Any, ptr: str) -> None:
        for i, node in enumerate(nodes or []):
            if not isinstance(node, dict):
                continue
            here = f"{ptr}/{i}"
            content = node.get("content")
            if isinstance(content, list):
                for pi, para in enumerate(content):
                    for ri, run in enumerate((para or {}).get("runs") or []):
                        text = str((run or {}).get("text", "")).replace("\\{{", "")
                        if text.count("{{") != text.count("}}"):
                            out.append(
                                {
                                    "pointer": f"{here}/content/{pi}/runs/{ri}/text",
                                    "rule": "SCENE_BROKEN_EXPRESSION",
                                    "node": node.get("id"),
                                    "message": "Expression is split between runs or not closed",
                                }
                            )
            walk(node.get("children"), f"{here}/children")
            if node.get("type") == "repeater":
                for part in ("item", "header", "footer", "emptyState"):
                    walk((node.get(part) or {}).get("children"), f"{here}/{part}/children")

    for si, sheet in enumerate(doc.get("sheets") or []):
        if isinstance(sheet, dict):
            walk(sheet.get("children"), f"/sheets/{si}/children")
    return out


def validate_scene(doc: Any) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, Any] | None]:
    """Return (errors, warnings, compiled plan or None)."""
    errors: list[dict[str, Any]] = []
    for err in scene_validator().iter_errors(doc):
        errors.append({"pointer": _pointer(err.absolute_path), "rule": err.validator, "message": err.message[:300]})
        if len(errors) >= MAX_ERRORS:
            break
    if errors:
        return errors, [], None
    errors.extend(_broken_expressions(doc))
    try:
        plan, ctx = compile_document(doc)
    except RenderError as exc:
        errors.append({"pointer": "/", "rule": exc.code, "message": exc.message})
        return errors, [], None
    errors.extend(
        {"pointer": "/", "rule": e["code"], **{k: v for k, v in e.items() if k != "code"}} for e in ctx.errors
    )
    warnings = list(ctx.warnings)
    return errors[:MAX_ERRORS], warnings, (None if errors else plan)


# Expression problems are normal while a user is typing (an unclosed ``{{`` between two autosaves): a draft
# with them is saved and they come back as warnings; validate/publish still treat them as errors.
DRAFT_TOLERATED = frozenset({"SCENE_BROKEN_EXPRESSION", "SCENE_EXPRESSION_INVALID"})


def ensure_valid_draft(doc: Any) -> list[dict[str, Any]]:
    """Autosave check: the JSON Schema must pass; expression errors are downgraded to warnings."""
    errors, warnings, _ = validate_scene(doc)
    hard = [e for e in errors if e.get("rule") not in DRAFT_TOLERATED]
    if hard:
        raise ApiError(422, "SCENE_INVALID", "Scene graph is invalid", hard)
    return [{"code": e.get("rule"), **{k: v for k, v in e.items() if k != "rule"}} for e in errors] + warnings


def ensure_valid_scene(doc: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
    errors, warnings, plan = validate_scene(doc)
    if errors or plan is None:
        raise ApiError(422, "SCENE_INVALID", "Scene graph is invalid", errors or [{"message": "invalid"}])
    return plan, warnings


def referenced_variables(plan: dict[str, Any]) -> set[str]:
    return set(plan.get("variables") or [])


def unknown_variables(plan: dict[str, Any], known: dict[str, str]) -> list[str]:
    """Variable paths used by the template that are not in the schema.

    Repeater/sheet loop names and system roots (page, sheet, doc, loop) are skipped. A path is accepted when
    it is in the schema, or when its longest known prefix is a scalar/array (``items.length``, ``tags[0]``).
    """
    local_names = {"page", "sheet", "doc", "loop", "now"}

    def collect_as(nodes: list[dict[str, Any]]) -> None:
        for n in nodes:
            if n.get("type") == "repeater":
                local_names.update((n.get("as", "item"), n.get("indexAs", "index")))
                for part in ("item", "header", "footer", "emptyState"):
                    if n.get(part):
                        collect_as(n[part]["children"])
            collect_as(n.get("children") or [])

    for sheet in plan["sheets"]:
        if sheet.get("repeat"):
            local_names.update((sheet["repeat"]["as"], sheet["repeat"]["indexAs"]))
        collect_as(sheet["children"])
    normalized = {k.replace("[]", ""): t for k, t in known.items()}
    out = []
    for path in sorted(referenced_variables(plan)):
        if path.split(".")[0].split("[")[0] in local_names:
            continue
        parts = path.replace("[]", "").split(".")
        if ".".join(parts) in normalized:
            continue
        prefix_type = next(
            (
                normalized[".".join(parts[:i])]
                for i in range(len(parts) - 1, 0, -1)
                if ".".join(parts[:i]) in normalized
            ),
            None,
        )
        if prefix_type is None or prefix_type == "object":
            out.append(path)
    return out


__all__ = ["collect_paths", "ensure_valid_draft", "ensure_valid_scene", "unknown_variables", "validate_scene"]
