"""ND0201: Unknown node key detection."""

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

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,
)

_data_text = files("valn8n_lib.data").joinpath("node_keys.json").read_text()
_data = json.loads(_data_text)
VALID_NODE_KEYS: set[str] = set(_data["keys"])

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


@register("ND0201", Severity.ERROR, description="Unknown node key")
def check_unknown_node_keys(
    workflow: dict[str, Any],
    path: Path,
    source_map: SourceMap = None,
    suggestions: SuggestionLevel = SuggestionLevel.FULL,
) -> list[Diagnostic]:
    """Flag keys on node objects that are not part of the INode schema."""
    diagnostics: list[Diagnostic] = []
    nodes = workflow.get("nodes", [])
    suffix = format_suggestions(VALID_NODE_KEYS, suggestions)
    for node_index, node in enumerate(nodes):
        if not isinstance(node, dict):
            continue
        node_name = node.get("name", "<unnamed>")
        for key in node:
            if key not in VALID_NODE_KEYS:
                json_pointer = f"/nodes/{node_index}/{key}"
                line = lookup_line(source_map, json_pointer)
                diagnostics.append(
                    Diagnostic(
                        file=str(path),
                        location=Location(node_name, key),
                        code=_RULE_CODE,
                        message=f'Unknown node key "{key}"' + suffix,
                        line=line,
                    )
                )
    return diagnostics
