"""Where variables are used (TZ I29): per template, the number of nodes that reference each schema path."""

from __future__ import annotations

import re
from collections import Counter
from typing import Any

from snapfile_render.compiler import CompileContext, Compiler, _expr

SYSTEM_ROOTS = {"page", "sheet", "doc", "loop", "now"}
_NESTED = ("children", "item", "header", "footer", "emptyState")
_INDEX = re.compile(r"\[\d*\]")


def _normalize(path: str, aliases: dict[str, str | None]) -> str | None:
    """``item.amount`` inside a repeater over ``deal.items`` -> ``deal.items.amount``; system roots -> None."""
    clean = _INDEX.sub("", path)
    head, _, rest = clean.partition(".")
    if head in aliases:
        base = aliases[head]
        if base is None:  # index alias or an alias of an unresolvable source
            return None
        return f"{base}.{rest}" if rest else base
    if head in SYSTEM_ROOTS:
        return None
    return clean


def _source_path(source: Any, aliases: dict[str, str | None]) -> str | None:
    if not isinstance(source, str) or not source.strip():
        return None
    ctx = CompileContext()
    _expr(source, ctx, "usage", "source")
    paths = sorted(ctx.variables)
    return _normalize(paths[0], aliases) if len(paths) == 1 else None


def _node_paths(raw: dict[str, Any], aliases: dict[str, str | None]) -> set[str]:
    shallow = {k: v for k, v in raw.items() if k not in _NESTED and k != "visible"}
    ctx = CompileContext()
    try:
        Compiler(ctx).node(shallow, str(raw.get("id") or "n"))
    except Exception:  # a broken node must not break the report
        return set()
    out = set()
    for p in ctx.variables:
        norm = _normalize(p, aliases)
        if norm:
            out.add(norm)
    return out


def document_usage(doc: dict[str, Any]) -> Counter[str]:
    counts: Counter[str] = Counter()

    def walk(nodes: Any, aliases: dict[str, str | None]) -> None:
        for raw in nodes or []:
            if not isinstance(raw, dict):
                continue
            counts.update(_node_paths(raw, aliases))
            inner = aliases
            if raw.get("type") == "repeater":
                inner = {
                    **aliases,
                    str(raw.get("as", "item")): _source_path(raw.get("source"), aliases),
                    str(raw.get("indexAs", "index")): None,
                }
            walk(raw.get("children"), inner)
            for part in _NESTED[1:]:
                cell = raw.get(part)
                if isinstance(cell, dict):
                    walk(cell.get("children"), inner)

    for sheet in (doc or {}).get("sheets") or []:
        if not isinstance(sheet, dict):
            continue
        aliases: dict[str, str | None] = {}
        rep = sheet.get("repeat")
        if isinstance(rep, dict) and rep.get("source"):
            src = _source_path(rep.get("source"), {})
            if src:
                counts[src] += 1
            aliases = {str(rep.get("as", "item")): src, str(rep.get("indexAs", "index")): None}
        if sheet.get("visibleIf"):
            ctx = CompileContext()
            _expr(sheet["visibleIf"], ctx, "sheet", "visibleIf")
            counts.update({p for p in (_normalize(x, aliases) for x in ctx.variables) if p})
        walk(sheet.get("children"), aliases)
    return counts
