"""
Intelligent Smart Detection - Uses Intelligence API
====================================================
DEPRECATION NOTICE: SmartDetection reimplemented matching logic.
This version delegates everything to the Intelligence API.

Migration Guide:
OLD: from fmatch.saas.ml.smart_detection import SmartDetection
NEW: from fmatch.saas.services.base_intelligent_service import BaseIntelligentService
"""

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

from ...services.base_intelligent_service import BaseIntelligentService

logger = logging.getLogger(__name__)


class IntelligentSmartDetection(BaseIntelligentService):
    """
    Replaces SmartDetection with intelligence API usage.

    ⚠️ DEPRECATED: The old SmartDetection was a parallel implementation
    of matching logic using rapidfuzz. This violates our architecture
    principle of centralized intelligence.

    This version is a wrapper that delegates to the Intelligence API.
    """

    def __init__(self, db_session=None):
        super().__init__(db_session)
        warnings.warn(
            "SmartDetection is deprecated. Use Intelligence API directly via BaseIntelligentService.",
            DeprecationWarning,
            stacklevel=2,
        )
        logger.warning(
            "SmartDetection initialized - consider migrating to Intelligence API directly"
        )

    async def detect_best_algorithm(
        self, sample_data: pd.DataFrame, column_name: str = None
    ) -> str:
        """
        Detect best matching algorithm for data.

        OLD: Custom algorithm selection logic with rapidfuzz
        NEW: Use intelligence API's algorithm recommendation

        Args:
            sample_data: Sample data to analyze
            column_name: Specific column to analyze

        Returns:
            Recommended algorithm name
        """
        logger.info("Using Intelligence API for algorithm detection")

        # Get intelligent configuration
        config = await self.get_intelligent_config(
            source_df=sample_data,
            target_df=sample_data,  # Self-comparison for analysis
            goal="algorithm_selection",
        )

        # Extract algorithm recommendation
        if column_name and column_name in config.get("algorithms", {}):
            return config["algorithms"][column_name]

        # Return the most common algorithm
        algos = config.get("algorithms", {}).values()
        if algos:
            from collections import Counter

            most_common = Counter(algos).most_common(1)[0][0]
            return most_common

        return "WRatio"  # Fallback default

    async def calculate_similarity(
        self, text1: str, text2: str, algorithm: str = None
    ) -> float:
        """
        Calculate similarity between two strings.

        OLD: Used rapidfuzz directly (fuzz.ratio, fuzz.token_set_ratio, etc.)
        NEW: Use engine client for consistent scoring

        Args:
            text1: First string
            text2: Second string
            algorithm: Optional algorithm override

        Returns:
            Similarity score (0-1)
        """
        if not text1 or not text2:
            return 0.0

        # Use engine for scoring
        score = await self.engine.score_pair(
            record1={"text": text1},
            record2={"text": text2},
            mappings=[
                {
                    "source": "text",
                    "reference": "text",
                    "weight": 1.0,
                    "algorithm": algorithm or "WRatio",
                }
            ],
        )

        return score / 100.0  # Convert to 0-1 scale

    async def smart_match(
        self,
        source_df: pd.DataFrame,
        target_df: Optional[pd.DataFrame] = None,
        threshold: float = None,
        **kwargs,
    ) -> Dict[str, Any]:
        """
        Perform intelligent matching.

        OLD: Custom matching logic with rapidfuzz
        NEW: Use intelligence API for everything

        Args:
            source_df: Source data
            target_df: Target data (None for deduplication)
            threshold: Optional threshold override (not recommended)
            **kwargs: Additional parameters

        Returns:
            Matching results
        """
        logger.warning(
            "SmartDetection.smart_match is deprecated. "
            "Using Intelligence API via match_with_intelligence()"
        )

        # Log migration suggestion
        logger.info(
            "MIGRATION TIP: Replace SmartDetection.smart_match() with "
            "BaseIntelligentService.match_with_intelligence()"
        )

        # Delegate to intelligence
        result = await self.match_with_intelligence(
            source_data=source_df,
            target_data=target_df,
            optimization_goal=kwargs.get("optimization_goal", "smart_detection"),
            **kwargs,
        )

        # Add deprecation notice to result
        if isinstance(result, dict):
            result["deprecation_notice"] = (
                "This result was generated using the deprecated SmartDetection. "
                "Please migrate to Intelligence API."
            )
            result["migration_guide"] = (
                "https://docs.example.com/migration/smart-detection-to-intelligence"
            )

        return result

    async def extract_features(
        self, record1: Dict, record2: Dict, columns: List[str]
    ) -> np.ndarray:
        """
        Extract matching features for ML.

        OLD: Used rapidfuzz for feature extraction
        NEW: Use engine's feature extraction

        Args:
            record1: First record
            record2: Second record
            columns: Columns to compare

        Returns:
            Feature vector
        """
        features = []

        for col in columns:
            val1 = str(record1.get(col, ""))
            val2 = str(record2.get(col, ""))

            # Get multiple algorithm scores as features
            for algo in ["WRatio", "TokenSetRatio", "JaroWinkler"]:
                score = await self.engine.score_pair(
                    record1={col: val1},
                    record2={col: val2},
                    mappings=[
                        {
                            "source": col,
                            "reference": col,
                            "weight": 1.0,
                            "algorithm": algo,
                        }
                    ],
                )
                features.append(score / 100.0)

        return np.array(features)

    async def process(self, *args, **kwargs):
        """Required by BaseIntelligentService"""
        return await self.smart_match(*args, **kwargs)

    @staticmethod
    def migration_guide():
        """
        Print migration guide for users.
        """
        guide = """
        ================================================================================
        MIGRATION GUIDE: SmartDetection -> Intelligence API
        ================================================================================

        The SmartDetection class is DEPRECATED because it:
        1. Reimplements matching logic instead of using the engine
        2. Uses rapidfuzz directly, violating our architecture
        3. Creates inconsistent results vs other services

        BEFORE (Old Way):
        ----------------
        from fmatch.saas.ml.smart_detection import SmartDetection

        detector = SmartDetection()
        result = await detector.smart_match(df1, df2, threshold=0.75)
        algo = await detector.detect_best_algorithm(sample_data)
        score = await detector.calculate_similarity("text1", "text2")

        AFTER (New Way):
        ---------------
        from fmatch.saas.services.base_intelligent_service import BaseIntelligentService

        class YourService(BaseIntelligentService):
            async def process(self, source_df, target_df):
                # Intelligence API handles everything!
                return await self.match_with_intelligence(
                    source_data=source_df,
                    target_data=target_df
                )

        service = YourService()
        result = await service.process(df1, df2)

        Benefits of Migration:
        - Consistent scoring across all services
        - Automatic algorithm selection
        - Dynamic threshold optimization
        - No hardcoded configurations
        - Centralized intelligence

        For more details, see: docs/migration/smart-detection.md
        ================================================================================
        """
        print(guide)
        return guide


def migrate_from_smart_detection():
    """Helper function to guide migration"""
    IntelligentSmartDetection.migration_guide()

    # Also create a migration report
    report = {
        "deprecated_class": "SmartDetection",
        "replacement_class": "BaseIntelligentService",
        "migration_urgency": "HIGH",
        "reason": "Direct rapidfuzz usage violates architecture",
        "affected_methods": [
            "smart_match()",
            "detect_best_algorithm()",
            "calculate_similarity()",
            "extract_features()",
        ],
        "migration_steps": [
            "1. Inherit from BaseIntelligentService",
            "2. Replace smart_match() with match_with_intelligence()",
            "3. Remove all rapidfuzz imports",
            "4. Use get_intelligent_config() for configuration",
            "5. Test with compliance validator",
        ],
    }

    return report


# Compatibility aliases for gradual migration
SmartDetection = IntelligentSmartDetection  # Alias for backward compatibility

__all__ = [
    "IntelligentSmartDetection",
    "SmartDetection",  # Deprecated alias
    "migrate_from_smart_detection",
]
