"""ND0102: Common mistake filter operation validation rule."""

from pathlib import Path
from typing import Any

from valn8n_lib.rules._nd_filter_common import (
    COMMON_MISTAKES,
    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,
)

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


@register("ND0102", Severity.ERROR, description="Common mistake filter operation")
def check_common_mistake_operations(
    workflow: dict[str, Any],
    path: Path,
    source_map: SourceMap = None,
    suggestions: SuggestionLevel = SuggestionLevel.FULL,
) -> list[Diagnostic]:
    """Flag filter operations that are common mistakes with a known correction."""
    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:
                correct = COMMON_MISTAKES[operation]
                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'Filter operation "{operation}" is a common mistake; '
                            f'did you mean "{correct}"?'
                        ),
                        line=line,
                    )
                )
    return diagnostics
