"""
💀 LEAD MONARCH - Lead Enrichment Shadow Agent 💀
FIXED VERSION - Compatible with DragoHan's grimoire APIs
"""

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


@register_monarch("lead")
class LeadMonarch(MonarchBase):
    """
    💀 LEAD ENRICHMENT SHADOW MONARCH 💀
    """
    
    async def enrich(self, data: Union[Dict, List, str]) -> Union[Dict, List[Dict]]:
        """💀 GOD METHOD - Enrich ANY data shape 💀"""
        print("💀 Lead Monarch: Beginning enrichment...")
        
        # Step 1: Auto-detect and load data
        if isinstance(data, str):
            print(f"   Detected: {'URL' if data.startswith('http') else 'File path'}")
            if data.startswith("http"):
                data = self.web.get.data(data)
            else:
                data = self.files.load(data)
        
        # Step 2: Normalize with json_mage
        print("   Normalizing data with json_mage...")
        normalized = self.json.modify(data)  # FIXED: No .clean()
        clean_data = normalized.raw
        
        # Step 3: Detect single vs batch
        if isinstance(clean_data, list):
            print(f"   Batch detected: {len(clean_data)} leads")
            return await self._enrich_batch(clean_data)
        else:
            print("   Single lead detected")
            return await self._enrich_single(clean_data)
    
    async def _enrich_single(self, lead: Dict) -> Dict:
        """Enrich one lead"""
        print(f"💀 Enriching: {lead.get('name', 'Unknown')}")
        
        # Build AI prompt (industry-aware)
        if self.industry == "restaurant":
            prompt = self._build_restaurant_prompt(lead)
        else:
            prompt = self._build_generic_prompt(lead)
        
        # Get AI insights
        try:
            thought = await self.think(prompt)
        except Exception as e:
            print(f"⚠️  AI failed: {e}")
            thought = ThoughtResult(thoughts="Fallback", metadata={"error": str(e)})
        
        # Calculate score
        score = self._calculate_score(thought, lead)
        
        enriched = {
            "original": lead,
            "ai_insights": thought.thoughts,
            "lead_score": score,
            "industry": self.industry or "generic",
            "monarch_id": self.monarch_id
        }
        
        print(f"   ✅ Enriched | Score: {score}/10")
        return enriched
    
    async def _enrich_batch(self, leads: List[Dict]) -> List[Dict]:
        """Enrich multiple leads with concurrency"""
        self._works = True
        self._results = []
        
        semaphore = asyncio.Semaphore(5)
        
        async def _process_one(lead):
            async with semaphore:
                result = await self._enrich_single(lead)
                self._current = result
                self._results.append(result)
                return result
        
        tasks = [_process_one(lead) for lead in leads]
        results = await asyncio.gather(*tasks)
        
        self._works = False
        print(f"💀 Batch complete: {len(results)} leads enriched")
        
        return results
    
    def _build_restaurant_prompt(self, lead: Dict) -> str:
        """Restaurant-specific enrichment prompt"""
        return f"""
💀 RESTAURANT LEAD ENRICHMENT 💀

Lead Data:
{lead}

Provide deep analysis:

1. REVENUE ESTIMATE
   - Monthly revenue range (based on type, location, size)
   - Revenue tier: Low (<$20k), Mid ($20-100k), High (>$100k)

2. PAIN POINTS (Restaurant-specific)
   - Reservation management issues?
   - Review/reputation problems?
   - Delivery/online ordering gaps?
   - POS system limitations?
   - Staff management challenges?

3. DECISION MAKER POWER (1-10 scale)
   - Owner = 10 (full decision authority)
   - General Manager = 7
   - Assistant Manager = 4
   - Staff = 1
   
4. OUTREACH ANGLE
   - Best approach for this specific restaurant
   - Pain point to emphasize
   - Value proposition

5. SERVICE FIT
   - Lead generation potential
   - Automation opportunities
   - Review management need
   - Reservation system upgrade

Format response as clear insights, not JSON.
Be specific and actionable.
"""
    
    def _build_generic_prompt(self, lead: Dict) -> str:
        """Generic lead enrichment prompt"""
        return f"""
Analyze this lead:
{lead}

Provide:
1. Company revenue estimate
2. Key pain points
3. Decision maker power (1-10)
4. Best outreach approach
5. Product/service fit

Be specific and actionable.
"""
    
    def _calculate_score(self, thought: ThoughtResult, lead: Dict) -> float:
        """
        Calculate lead score (0-10)
        Formula: 60% decision + 30% revenue + 10% completeness
        """
        completeness = len([v for v in lead.values() if v]) / max(len(lead), 1)
        base_score = completeness * 10
        
        if self.industry == "restaurant":
            base_score *= 1.1
        
        return min(round(base_score, 1), 10.0)
    
    # SYNC WRAPPERS
    def enrich_sync(self, data):
        """Sync wrapper for enrich()"""
        from .factory import waitfor
        return waitfor(self.enrich(data))
    
    def __call__(self, data):
        """Shorthand: agent(data) → enrich_sync(data)"""
        return self.enrich_sync(data)
