"""
💀 MONARCH FACTORY & SUMMON SYSTEM 💀
Tool injection and agent summoning
"""

import asyncio
from typing import Dict, Any, Optional
from .registry import get_monarch_class, list_monarchs


def waitfor(coro):
    """
    💀 DragoHan's Sync Wrapper 💀
    
    Run async code synchronously without thinking about event loops.
    
    Usage:
        result = waitfor(agent.enrich(data))
    
    This is your bridge between async agent internals and sync user code.
    """
    try:
        # Check if already in async context
        loop = asyncio.get_running_loop()
        raise RuntimeError(
            "❌ Cannot use waitfor() inside async context!\n"
            "💀 You're already in async land.\n"
            "   Use: await agent.enrich(data)\n"
            "   NOT: waitfor(agent.enrich(data))"
        )
    except RuntimeError as e:
        if "no running event loop" in str(e).lower():
            # Safe to use asyncio.run()
            return asyncio.run(coro)
        else:
            # Re-raise our custom error
            raise


def build_default_tools() -> Dict[str, Any]:
    """
    💀 AUTO-INJECT ALL GRIMOIRE TOOLS 💀
    
    Loads all your grimoire modules and makes them available to monarchs.
    
    Returns:
        Dict with:
        - Stateful tools (classes): brain.Brain, experience.Experience
        - Stateless tools (modules): json_mage, simple_file, web, dupes
    """
    try:
        # Try package-style imports first
        from grimoire import brain, json_mage, simple_file, duplicates, experience
        from grimoire.internet import getter
    except ImportError:
        # Fall back to direct imports
        import brain
        import json_mage
        import simple_file
        import duplicates
        import experience
        from internet import getter
    
    tools = {
        # Stateful (classes - monarchs will lazy-load instances)
        "brain": brain.Brain,
        "experience": experience.Experience,
        
        # Stateless (modules - direct access)
        "json": json_mage,
        "files": simple_file,
        "web": getter,
        "dupes": duplicates,
    }
    
    print("💀 Tools loaded: brain, json, files, web, dupes, experience")
    return tools


def summon(name: str, industry: Optional[str] = None, **kwargs):
    """
    💀 SUMMON A SHADOW MONARCH 💀
    
    Create an agent with all grimoire tools auto-injected.
    
    Usage:
        agent = summon("lead")
        agent = summon("lead", industry="restaurant")
        agent = summon("data")
    
    Args:
        name: Monarch type ("lead", "data", "ops")
        industry: Optional industry specialization ("restaurant", etc)
        **kwargs: Additional config passed to monarch
    
    Returns:
        Fully initialized Monarch with tools injected
    
    Raises:
        ValueError: If monarch name not found in registry
    """
    # Get monarch class from registry
    cls = get_monarch_class(name)
    
    if cls is None:
        available = ", ".join(list_monarchs()) or "none (did you import monarchs?)"
        raise ValueError(
            f"❌ Unknown Shadow Monarch: '{name}'\n"
            f"💀 Available: {available}\n"
            f"   Make sure monarch module is imported."
        )
    
    # Build tools
    tools = build_default_tools()
    
    # Summon the monarch
    print(f"💀 Summoning {name.upper()} Shadow Monarch...")
    if industry:
        print(f"   Industry: {industry}")
    
    return cls(tools=tools, industry=industry, **kwargs)
