"""Graph helper utilities."""

from __future__ import annotations

from typing import Iterable, List

from ..adt_types import ResourceNode, ResourceRelationship


def ensure_unique_nodes(nodes: Iterable[ResourceNode]) -> List[ResourceNode]:
    """Remove duplicate nodes preserving last occurrence."""

    seen = {}
    for node in nodes:
        if node.id in seen:
            del seen[node.id]
        seen[node.id] = node
    return list(seen.values())


def build_graph_edges(
    nodes: Iterable[ResourceNode],
    include_relationships: bool,
) -> List[ResourceRelationship]:
    """Create inferred relationships if required."""

    if not include_relationships:
        return []

    node_map = {node.id: node for node in nodes}
    edges: List[ResourceRelationship] = []
    for node in node_map.values():
        for dependency_id in node.dependencies:
            if dependency_id in node_map:
                edges.append(
                    ResourceRelationship(
                        source_id=node.id,
                        target_id=dependency_id,
                        relation_type="depends_on",
                    )
                )
    return edges
