"""
Helper functions for handling deduplication mode in matching engine.
"""

from typing import List, Dict, Any, Tuple
import pandas as pd


def filter_dedup_matches(
    matches: List[Dict[str, Any]], src_id_col: str, ref_id_col: str
) -> List[Dict[str, Any]]:
    """
    Filter matches to remove self-matches and duplicate pairs in dedup mode.
    Keeps only (i,j) where i < j to avoid both (i,j) and (j,i).
    """
    filtered = []
    seen_pairs = set()

    for match in matches:
        src_id = match.get(src_id_col or "s_id")
        ref_id = match.get(ref_id_col or "r_id")

        # Skip self-matches
        if src_id == ref_id:
            continue

        # Create canonical pair (smaller id first)
        pair = (min(src_id, ref_id), max(src_id, ref_id))

        # Skip if we've seen this pair
        if pair in seen_pairs:
            continue

        seen_pairs.add(pair)
        filtered.append(match)

    return filtered


def get_dedup_indices(n: int) -> List[Tuple[int, int]]:
    """
    Get upper triangle indices for dedup comparisons.
    Returns list of (i, j) tuples where i < j.
    """
    indices = []
    for i in range(n):
        for j in range(i + 1, n):
            indices.append((i, j))
    return indices


def filter_cdist_scores_dedup(
    scores_df: pd.DataFrame, src_id_col: str, ref_id_col: str
) -> pd.DataFrame:
    """
    Filter cdist scores to keep only upper triangle for dedup mode.
    Assumes scores_df has columns for source and reference indices/IDs.
    """
    # Remove self-matches
    scores_df = scores_df[scores_df[src_id_col] != scores_df[ref_id_col]]

    # Keep only upper triangle (where src < ref)
    scores_df = scores_df[scores_df[src_id_col] < scores_df[ref_id_col]]

    return scores_df
