"""
ChunkHive Dependency Expander
=============================

Expands ranked chunks using RelationshipGraph.

Adds:
- Called functions
- Class methods
- Structural neighbors

Uses chunk.chunk_id as canonical identity.
"""

from typing import List, Set, Any


class DependencyExpander:
    """
    Expands ranked chunks using RelationshipGraph.
    """

    def __init__(self, graph):
        self.graph = graph

    def expand(
        self,
        base_chunks: List[Any],
        max_expansion: int = 10,
    ) -> List[Any]:
        """
        Expand base chunks using graph relationships.

        Returns:
            Ordered unique list of chunks.
        """

        expanded: List[Any] = []
        visited_ids: Set[str] = set()

        def add_chunk(chunk):
            if not hasattr(chunk, "chunk_id"):
                return

            cid = chunk.chunk_id

            if cid not in visited_ids:
                visited_ids.add(cid)
                expanded.append(chunk)

        # 1️⃣ Add base chunks first (priority order)
        for chunk in base_chunks:
            add_chunk(chunk)

        # 2️⃣ Expand relationships
        for chunk in base_chunks:

            if len(expanded) >= max_expansion:
                break

            if not hasattr(chunk, "chunk_id"):
                continue

            related_ids = self.graph.get_related(chunk.chunk_id)

            for rel_id in related_ids:

                if len(expanded) >= max_expansion:
                    break

                related_chunk = self.graph.get_chunk(rel_id)

                if related_chunk:
                    add_chunk(related_chunk)

        return expanded
