# fmatch/core/telemetry.py
import hashlib
import logging
from datetime import datetime
from typing import Dict, Any, Optional, List

# Add logger for sending batches
log = logging.getLogger(__name__)


class TelemetryCollector:
    """Collects anonymized usage data for ID detection and icon accuracy improvement"""

    def __init__(self, enabled: bool = True):
        self.enabled = enabled
        self.events = []

    def record_id_detection(
        self,
        dataset_hash: str,
        detection_result: Dict[str, Any],
        user_override: Optional[str] = None,
        file_source: Optional[str] = None,
    ):
        """Record ID detection event"""
        if not self.enabled:
            return

        event = {
            "timestamp": datetime.utcnow().isoformat(),
            "event_type": "id_detection",
            "dataset_hash": dataset_hash,  # Anonymized
            "auto_selected": detection_result.get("selected"),
            "confidence": detection_result.get("confidence"),
            "detected_system": detection_result.get("system"),
            "score": detection_result.get("score"),
            "user_override": user_override is not None,
            "override_column": user_override,
            "file_source": self._anonymize_source(file_source),
            "top_candidates": [
                {
                    "score": c["score"],
                    "system": c.get("system"),
                    "patterns": len(c.get("patterns", [])),
                }
                for c in detection_result.get("all_candidates", [])[:3]
            ],
        }

        self.events.append(event)

        # Batch send every 10 events
        if len(self.events) >= 10:
            self._send_batch()

    def record_icon_assignment(
        self,
        dataset_hash: str,
        column_stats: Dict[str, Any],
        assigned_icons: List[str],
        confidence_scores: Dict[str, float],
        source_system: Optional[str] = None,
    ):
        """Record which icons were assigned to a column"""
        if not self.enabled:
            return

        event = {
            "timestamp": datetime.utcnow().isoformat(),
            "event_type": "icon_assignment",
            "dataset_hash": dataset_hash,
            "column_hash": hashlib.md5(column_stats["name"].encode()).hexdigest()[:8],
            "assigned_icons": assigned_icons,
            "confidence_scores": confidence_scores,
            "column_metrics": {
                "fill_rate": column_stats.get("fill_rate"),
                "distinct_ratio": column_stats.get("distinct_ratio"),
                "inferred_type": column_stats.get("inferred_type"),
                "detected_patterns": column_stats.get("detected_patterns", []),
            },
            "source_system": source_system,
        }
        self.events.append(event)

    def record_icon_override(
        self,
        dataset_hash: str,
        column_name: str,
        original_icons: List[str],
        user_action: str,  # 'removed', 'added', 'changed'
        new_icons: List[str],
        user_feedback: Optional[str] = None,
    ):
        """Record when users disagree with icon assignments"""
        if not self.enabled:
            return

        event = {
            "timestamp": datetime.utcnow().isoformat(),
            "event_type": "icon_override",
            "dataset_hash": dataset_hash,
            "column_hash": hashlib.md5(column_name.encode()).hexdigest()[:8],
            "original_icons": original_icons,
            "user_action": user_action,
            "new_icons": new_icons,
            "user_feedback": user_feedback,
        }
        self.events.append(event)

        # Immediate send for overrides (high-value signal)
        self._send_batch()

    def _anonymize_source(self, source: Optional[str]) -> Optional[str]:
        """Anonymize file source while preserving system info"""
        if not source:
            return None

        # Detect CRM system from path
        source_lower = source.lower()
        if "salesforce" in source_lower:
            return "salesforce_export"
        elif "hubspot" in source_lower:
            return "hubspot_export"
        elif "dynamics" in source_lower:
            return "dynamics_export"
        elif ".csv" in source_lower:
            return "generic_csv"
        else:
            return "unknown"

    def _send_batch(self):
        """Send telemetry batch (implement based on your infrastructure)"""
        # This would send to your telemetry endpoint
        # For now, just log locally
        if self.events:
            log.info(f"Telemetry batch: {len(self.events)} events")
            self.events = []
