"""ND0101: Invalid filter operation validation rule."""

from pathlib import Path
from typing import Any

from valn8n_lib.rules._nd_filter_common import (
    COMMON_MISTAKES,
    VALID_OPS,
    find_filter_conditions,
    to_json_pointer,
)
from valn8n_lib.rules.registry import SourceMap, register
from valn8n_lib.source_map import lookup_line
from valn8n_lib.types import (
    Diagnostic,
    Location,
    RuleCode,
    Severity,
    SuggestionLevel,
    format_suggestions,
)

_RULE_CODE = RuleCode("ND0101", Severity.ERROR)


@register("ND0101", Severity.ERROR, description="Invalid filter operation for type")
def check_filter_operations(
    workflow: dict[str, Any],
    path: Path,
    source_map: SourceMap = None,
    suggestions: SuggestionLevel = SuggestionLevel.FULL,
) -> list[Diagnostic]:
    """Check that filter conditions use valid operations for their type."""
    diagnostics: list[Diagnostic] = []
    nodes = workflow.get("nodes", [])
    for node_index, node in enumerate(nodes):
        node_name = node.get("name", "<unnamed>")
        for field_path, type_name, operation in find_filter_conditions(node.get("parameters", {})):
            if operation in COMMON_MISTAKES:
                continue
            valid = VALID_OPS.get(type_name)
            if valid is None:
                continue
            if operation not in valid:
                suffix = format_suggestions(valid, suggestions)
                json_pointer = to_json_pointer(node_index, field_path)
                line = lookup_line(source_map, json_pointer)
                diagnostics.append(
                    Diagnostic(
                        file=str(path),
                        location=Location(node_name, field_path),
                        code=_RULE_CODE,
                        message=(
                            f'Invalid filter operation "{operation}" for type "{type_name}"'
                            + suffix
                        ),
                        line=line,
                    )
                )
    return diagnostics
