"""ND0802: Complex node missing notes."""

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

_RULE_CODE = RuleCode("ND0802", Severity.HINT)

_COMPLEX_TYPES = {
    "n8n-nodes-base.code",
    "n8n-nodes-base.function",
    "n8n-nodes-base.functionItem",
    "n8n-nodes-base.httpRequest",
    "n8n-nodes-base.switch",
    "n8n-nodes-base.if",
    "n8n-nodes-base.merge",
}


@register(
    "ND0802",
    Severity.HINT,
    description="Complex node missing notes",
    strict=False,
)
def check_complex_node_missing_notes(
    workflow: dict[str, Any],
    path: Path,
    source_map: SourceMap = None,
    suggestions: SuggestionLevel = SuggestionLevel.FULL,
) -> list[Diagnostic]:
    """Flag complex nodes (Code, HTTP Request, Switch, IF, Merge) with empty or missing notes."""
    diagnostics: list[Diagnostic] = []
    fname = str(path)

    for i, node in enumerate(workflow.get("nodes", [])):
        if node.get("disabled"):
            continue

        node_type = node.get("type", "")
        if node_type not in _COMPLEX_TYPES:
            continue

        notes = node.get("notes", "").strip()
        if notes:
            continue

        node_name = node.get("name", f"node[{i}]")
        pointer = f"/nodes/{i}/notes"
        line = lookup_line(source_map, pointer)
        diagnostics.append(
            Diagnostic(
                file=fname,
                location=Location(node_name, "notes"),
                code=_RULE_CODE,
                message=(
                    f'Complex node "{node_name}" ({node_type}) has no notes;'
                    " consider documenting its purpose"
                ),
                line=line,
            ),
        )

    return diagnostics
