from typing import Optional
import pandas as pd


class InterfaceValidator:

    def validate_unique_device_port_group(
        self,
        df: pd.DataFrame,
        device_column_name: str,
        port_column_name: str,
        side_label: Optional[str] = None,
    ) -> list:
        """Check for duplicate connections on same ports"""
        errors = []
        group_info = df.groupby([device_column_name, port_column_name]).agg(
            count=(port_column_name, "size"),
            indices=(port_column_name, lambda s: list(s.index)),
        )

        dupes = group_info[group_info["count"] > 1]

        for (ne, port), row in dupes.sort_index().iterrows():
            count = row["count"]
            indices = row["indices"]
            if side_label:
                errors.append(
                    f"[Side {side_label}] Port '{port}' on Network Element '{ne}' "
                    f"is defined {count} times (rows {indices}). "
                    f"Each port may only be defined once."
                )
            else:
                errors.append(
                    f"Port '{port}' on Network Element '{ne}' "
                    f"is defined {count} times (rows {indices}). "
                    f"Each port may only be defined once."
                )

        return errors
