"""
💀 DATA MONARCH - Data Analysis Shadow Agent 💀
FIXED VERSION - Compatible with DragoHan's grimoire APIs
"""

from typing import Dict, Any, Union
from .core import MonarchBase, ThoughtResult
from .registry import register_monarch


@register_monarch("data")
class DataMonarch(MonarchBase):
    """
    💀 DATA ANALYSIS SHADOW MONARCH 💀
    """
    
    async def analyze(self, data: Union[str, Dict, list], 
                     sample_size: int = 500,
                     dedupe_threshold: float = 0.05) -> Dict[str, Any]:
        """💀 Analyze dataset with AI insights 💀"""
        print("💀 Data Monarch: Beginning analysis...")
        
        # Load data if file path
        if isinstance(data, str):
            print(f"   Loading: {data}")
            data = self.files.load(data)
        
        # Normalize with json_mage
        print("   Normalizing data...")
        normalized = self.json.modify(data)  # FIXED: No .clean()
        clean_data = normalized.raw
        
        # Get summary stats
        summary = normalized.summary()
        
        # Find duplicates - FIXED: Use smart_duplicate_check
        print("   Checking for duplicates...")
        if isinstance(clean_data, list):
            # FIXED: Use correct API
            dupe_result = self.dupes.smart_duplicate_check(clean_data)
            if isinstance(dupe_result, dict):
                dupe_count = dupe_result.get('duplicate_count', 0)
                total = dupe_result.get('total_items', len(clean_data))
            else:
                dupe_count = 0
                total = len(clean_data)
            
            dupe_rate = dupe_count / total if total > 0 else 0
        else:
            dupe_count = 0
            dupe_rate = 0
        
        # Sample for AI analysis (if large dataset)
        if isinstance(clean_data, list) and len(clean_data) > sample_size:
            sample = clean_data[:sample_size]
            print(f"   Sampling {sample_size} items for AI analysis...")
        else:
            sample = clean_data
        
        # AI analysis
        print("   Generating AI insights...")
        prompt = f"""
Analyze this dataset:

Summary: {summary}
Duplicate rate: {dupe_rate:.1%}
Sample data: {str(sample)[:1000]}

Provide:
1. Data quality score (0-10)
2. Key patterns found
3. Anomalies detected
4. Recommended actions
5. Business insights

Be specific and actionable.
"""
        
        thought = await self.think(prompt)
        
        # Build report
        report = {
            "data_quality_score": self._calculate_quality_score(summary, dupe_rate),
            "summary": summary,
            "duplicates": {
                "count": dupe_count,
                "rate": f"{dupe_rate:.1%}",
                "threshold_exceeded": dupe_rate > dedupe_threshold
            },
            "ai_analysis": thought.thoughts,
            "recommended_actions": self._generate_recommendations(dupe_rate, summary),
            "monarch_id": self.monarch_id
        }
        
        print(f"💀 Analysis complete | Quality: {report['data_quality_score']}/10")
        return report
    
    def _calculate_quality_score(self, summary: Dict, dupe_rate: float) -> float:
        """Calculate data quality score (0-10)"""
        base_score = 10.0
        
        if dupe_rate > 0.05:
            base_score -= (dupe_rate * 20)
        
        return max(round(base_score, 1), 0.0)
    
    def _generate_recommendations(self, dupe_rate: float, summary: Dict) -> list:
        """Generate actionable recommendations"""
        recs = []
        
        if dupe_rate > 0.05:
            recs.append("Remove duplicates (>5% found)")
        
        if dupe_rate > 0.20:
            recs.append("CRITICAL: 20%+ duplicates - clean immediately")
        
        recs.append("Validate data types")
        recs.append("Add data validation layer")
        
        return recs
    
    # SYNC WRAPPERS
    def analyze_sync(self, data, **kwargs):
        """Sync wrapper for analyze()"""
        from .factory import waitfor
        return waitfor(self.analyze(data, **kwargs))
    
    def __call__(self, data, **kwargs):
        """Shorthand: agent(data) → analyze_sync(data)"""
        return self.analyze_sync(data, **kwargs)
