"""
Intelligence utility functions for direct use by services.
These are simplified versions of the API endpoints that work with DataFrames directly.
"""

import pandas as pd
from typing import Dict, Any, List, Optional
import logging

logger = logging.getLogger(__name__)


def analyze_dataframes(
    source_df: pd.DataFrame, target_df: Optional[pd.DataFrame] = None
) -> Dict[str, Any]:
    """Direct DataFrame analysis without API calls"""
    from ..api.v2.intelligence import assess_data_quality

    # Use the existing assess_data_quality function
    quality = assess_data_quality(source_df, target_df)

    # Add basic analysis results
    result = {
        "quality": quality,
        "source_rows": len(source_df),
        "source_columns": len(source_df.columns),
        "mappings": {"suggested": []},  # Will be filled by suggest_mappings
    }

    if target_df is not None:
        result["target_rows"] = len(target_df)
        result["target_columns"] = len(target_df.columns)

    return result


async def suggest_dataframe_mappings(
    source_df: pd.DataFrame,
    target_df: pd.DataFrame,
    threshold: int = 70,
    enable_multi_algo: bool = True,
) -> List[Dict[str, Any]]:
    """Direct DataFrame mapping suggestions without API calls"""
    mappings = []

    # Simple column name matching for now
    source_cols = set(source_df.columns)
    target_cols = set(target_df.columns)

    # Exact matches
    for col in source_cols:
        if col in target_cols:
            mappings.append(
                {
                    "source": col,
                    "ref": col,
                    "weight": 1.0,
                    "confidence": 100,
                    "algorithm": "exact",
                }
            )

    # If no exact matches, try fuzzy matching
    if not mappings:
        # Simple fuzzy matching based on column name similarity
        for source_col in source_cols:
            source_lower = source_col.lower().replace("_", "").replace(" ", "")
            for target_col in target_cols:
                target_lower = target_col.lower().replace("_", "").replace(" ", "")

                # Check for common patterns
                if source_lower in target_lower or target_lower in source_lower:
                    mappings.append(
                        {
                            "source": source_col,
                            "ref": target_col,
                            "weight": 0.8,
                            "confidence": 80,
                            "algorithm": "fuzzy",
                        }
                    )
                    break

    return mappings


async def optimize_dataframe_blocking(
    source_df: pd.DataFrame,
    target_df: Optional[pd.DataFrame] = None,
    mode: str = "balanced",
) -> Dict[str, Any]:
    """Direct DataFrame blocking optimization without API calls"""
    # Simple blocking strategy based on data size
    row_count = len(source_df)

    if row_count < 1000:
        # Small dataset - no blocking needed
        return {"apply_blocking": False, "method": "none", "fields": []}
    elif row_count < 10000:
        # Medium dataset - simple blocking
        return {
            "apply_blocking": True,
            "method": "sorted_neighborhood",
            "window_size": 3,
            "fields": [],  # Will be determined by field selection
        }
    else:
        # Large dataset - aggressive blocking
        return {
            "apply_blocking": True,
            "method": "recordlinkage",
            "blocking_rules": ["first_letter", "soundex"],
            "fields": [],  # Will be determined by field selection
        }


async def auto_configure_dataframes(
    source_df: pd.DataFrame,
    target_df: Optional[pd.DataFrame] = None,
    goal: str = "balanced",
    constraints: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Direct DataFrame auto-configuration without API calls"""
    # Analyze data
    analysis = analyze_dataframes(source_df, target_df)

    # Get mappings if target exists
    mappings = []
    if target_df is not None:
        mappings = await suggest_dataframe_mappings(source_df, target_df)

    # Get blocking strategy
    blocking = await optimize_dataframe_blocking(source_df, target_df, goal)

    # Determine threshold based on goal
    if goal == "speed":
        threshold = 0.85
    elif goal == "accuracy":
        threshold = 0.70
    else:  # balanced
        threshold = 0.75

    return {
        "analysis": analysis,
        "mappings": mappings,
        "blocking": blocking,
        "threshold": threshold,
        "mode": "dedupe" if target_df is None else "link",
    }
