"""ND0502: Detect credential entries with empty/missing ID."""

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("ND0502", Severity.WARNING)


@register("ND0502", Severity.WARNING, description="Empty credential ID", strict=False)
def check_empty_credential_id(
    workflow: dict[str, Any],
    path: Path,
    source_map: SourceMap = None,
    suggestions: SuggestionLevel = SuggestionLevel.FULL,
) -> list[Diagnostic]:
    """Flag credential entries where the id field is empty or missing."""
    diagnostics: list[Diagnostic] = []
    fname = str(path)

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

        node_creds = node.get("credentials")
        if not isinstance(node_creds, dict):
            continue

        node_name = node.get("name", f"node[{i}]")
        for cred_type, cred_value in node_creds.items():
            if not isinstance(cred_value, dict):
                continue
            if not cred_value.get("id"):
                pointer = f"/nodes/{i}/credentials/{cred_type}/id"
                line = lookup_line(source_map, pointer)
                diagnostics.append(
                    Diagnostic(
                        file=fname,
                        location=Location(node_name, f"credentials/{cred_type}"),
                        code=_RULE_CODE,
                        message=f'Credential "{cred_type}" has no ID configured',
                        line=line,
                    ),
                )

    return diagnostics
