"""Shared helpers for ND0101/ND0102 filter operation rules."""

import json
from importlib.resources import files
from typing import Any

_data_text = files("valn8n_lib.data").joinpath("filter_operators.json").read_text()
_data = json.loads(_data_text)
VALID_OPS: dict[str, set[str]] = {k: set(v) for k, v in _data.items() if k != "_meta"}

_mistakes_text = files("valn8n_lib.data").joinpath("common_mistakes.json").read_text()
_mistakes_data = json.loads(_mistakes_text)
COMMON_MISTAKES: dict[str, str] = _mistakes_data["mistakes"]


def find_filter_conditions(
    obj: Any,
    path: str = "",
) -> list[tuple[str, str, str]]:
    """Recursively find dicts with operator.type + operator.operation.

    Returns list of (field_path, type, operation).
    """
    results: list[tuple[str, str, str]] = []
    if isinstance(obj, dict):
        op = obj.get("operator")
        if isinstance(op, dict) and "type" in op and "operation" in op:
            results.append((path, op["type"], op["operation"]))
        for key, value in obj.items():
            results.extend(find_filter_conditions(value, f"{path}.{key}" if path else key))
    elif isinstance(obj, list):
        for i, item in enumerate(obj):
            results.extend(find_filter_conditions(item, f"{path}.{i}"))
    return results


def to_json_pointer(node_index: int, field_path: str) -> str:
    """Convert node index + dotted field path to a JSON pointer.

    E.g. node_index=1, field_path="conditions.conditions.0" →
    "/nodes/1/parameters/conditions/conditions/0"
    """
    parts = field_path.split(".")
    pointer_parts = [f"/nodes/{node_index}/parameters"] + [f"/{p}" for p in parts]
    return "".join(pointer_parts)
