# preprocessing/core/pre_blocking.py
import pandas as pd
import logging
from typing import Tuple

log = logging.getLogger(__name__)


class BlockingKeyGenerator:
    """Generates blocking keys for record linkage"""

    def generate_blocking_keys(
        self, df: pd.DataFrame, block_col: str, key_length: int
    ) -> Tuple[pd.DataFrame, dict]:
        """Generate blocking keys from specified column"""
        result_df = df.copy()

        if block_col in df.columns:
            # CRITICAL: Use the exact column name the engine expects
            result_df["_active_block_key_"] = (  # Changed to lowercase
                df[block_col]
                .astype(str)
                .str.lower()
                .str.replace(r"[^a-z0-9]", "", regex=True)
                .str[:key_length]
                .fillna("")  # Handle any NaN values
            )

            # Log statistics
            unique_keys = result_df["_active_block_key_"].nunique()
            empty_keys = (result_df["_active_block_key_"] == "").sum()

            log.info(
                f"Generating blocking keys from column '{block_col}' with length {key_length}"
            )
            log.info(f"Created {unique_keys} unique blocks, {empty_keys} empty")

        else:
            log.warning(f"Blocking column '{block_col}' not found")
            result_df["_active_block_key_"] = ""

        return result_df, {}
