"""Connector renaming convention for unique labeling across patterns."""

from collections import defaultdict

from pydexpi.syndata.pattern import Connector, Pattern


class ConnectorRenamingConvention:
    """Class to manage the renaming of connectors in a pattern to generate unique labels across
    patterns."""

    def __init__(self):
        """Initialize the ConnectorRenamingConvention class."""
        # Dictionary to keep track of the number of times a pattern has been encountered.
        self.encountered_pattern_counter = defaultdict(int)

    def rename_connectors(
        self, pattern_to_rename: Pattern, connectors_to_skip: list[Connector] = None
    ) -> None:
        """Rename connectors in the given pattern to unique labels accross patterns.

        The new names are obtained from calling _make_new_connector_name() for each connector
        internally.

        Parameters
        ----------
        pattern_to_rename : Pattern
            The pattern whose connectors are to be renamed.
        connectors_to_skip : list[Connector], optional
            A list of connectors to skip renaming.

        Returns
        -------
        None: The pattern is modified in place.
        """
        connectors_to_skip = connectors_to_skip or []
        for connector in list(pattern_to_rename.connectors.values()):
            if connector in connectors_to_skip:
                continue
            else:
                new_label = self._make_new_connector_name(connector, pattern_to_rename)
                pattern_to_rename.relabel_connector(connector, new_label)

        # Increment the counter for the encountered pattern
        self.encountered_pattern_counter[pattern_to_rename.label] += 1

    def _make_new_connector_name(self, the_connector: Connector, parent_pattern: Pattern) -> str:
        """Create a new connector name based on the parent pattern's name and the connector's type.

        The new name is generated by combining the parent pattern's label, the connector's type,
        and a counter. This ensures unique labeling accross patterns.

        Parameters
        ----------
        the_connector : Connector
            The connector for which to create a new name.
        parent_pattern : Pattern
            The parent pattern to which the connector belongs.

        Returns
        -------
        str
            The new connector name.
        """
        current_pattern_index = self.encountered_pattern_counter[parent_pattern.label]
        return f"{parent_pattern.label}_{current_pattern_index}_{the_connector.label}"

    def reset(self) -> None:
        """Reset the counter for all encountered patterns."""
        self.encountered_pattern_counter = defaultdict(int)
