"""
AI Models Configuration System
Provides helper functions to work with AI models from database
"""

from .db_manager import (
    get_all_ai_models,
    get_ai_model_by_name,
    get_ai_models_by_provider,
    get_ai_models_by_capability
)

# Provider mapping from database names to g4f provider names
PROVIDER_MAPPING = {
    "Perplexity": "Perplexity",
    "PerplexityLabs": "Perplexity",
    "OpenAI": "openai",
    "Anthropic": "Anthropic",
    "Claude": "Claude",
    "Groq": "Groq",
    "Google": "google",
    "HuggingChat": "HuggingChat",
    "PollinationsAI": "PollinationsAI",
    "Pollinations": "PollinationsAI",
    "AnyProvider": "AnyProvider",  # Fallback
}


def map_provider_name(db_provider: str) -> str:
    """Map database provider name to g4f provider name"""
    return PROVIDER_MAPPING.get(db_provider, db_provider)


def get_default_model():
    """Get the default model name to use in frontend - only returns working models"""
    try:
        # Get only active/working models
        all_models = get_all_ai_models(active_only=True)
        if all_models:
            # First see if gpt-4o is working
            for m in all_models:
                if m["name"] == "perplexity":
                    return "perplexity"
            
            # Return first working model as fallback
            return all_models[0]["name"]
        
        # Ultimate fallback
        return "perplexity"
    except:
        return "perplexity"


def get_model_config(model_name: str) -> dict:
    """Get configuration for a specific model from database"""
    try:
        model = get_ai_model_by_name(model_name)
        
        # Check if model exists and is working/active (not inactive or deprecated)
        if model:
            model_status = model.get('status', 'inactive')
            if model_status not in ('active', 'working'):
                print(f"⚠️  Model '{model_name}' has status '{model_status}', finding working alternative...")
                model = None  # Force fallback to a working model
        
        if model:
            db_provider = model.get('provider', 'PollinationsAI')
            mapped_provider = map_provider_name(db_provider)
            
            print(f"📦 Loaded model from DB: {model_name}")
            print(f"   Model: {model.get('model', 'N/A')}")
            print(f"   Status: {model.get('status', 'N/A')}")
            print(f"   DB Provider: {db_provider}")
            print(f"   Mapped Provider: {mapped_provider}")
            
            # Create a copy for g4f usage with mapped provider
            g4f_model = model.copy()
            g4f_model['provider'] = mapped_provider
            return g4f_model
        
        # Fallback to first working model if requested model not found or inactive
        print(f"⚠️  Model '{model_name}' not found or inactive in DB, using first working model")
        all_models = get_all_ai_models(active_only=True)  # Only get working/active models
        if all_models:
            fallback = all_models[0]
            db_provider = fallback.get('provider', 'PollinationsAI')
            mapped_provider = map_provider_name(db_provider)
            fallback_copy = fallback.copy()
            fallback_copy['provider'] = mapped_provider
            print(f"   Fallback: {fallback.get('name', 'N/A')} (Status: {fallback.get('status')}, DB Provider: {db_provider} -> Mapped: {mapped_provider})")
            return fallback_copy
        
        # Ultimate fallback
        print(f"❌ Database is empty! Cannot load any models.")
        return {
            'name': 'gpt-4',
            'model': 'gpt-4',
            'provider': 'PollinationsAI',
            'description': 'Default GPT-4 model',
            'capabilities': ['text', 'code', 'vision']
        }
    except Exception as e:
        print(f"❌ Error loading model from database: {e}")
        return {
            'name': 'gpt-4',
            'model': 'gpt-4',
            'provider': 'PollinationsAI',
            'description': 'Default GPT-4 model',
            'capabilities': ['text', 'code', 'vision']
        }


def get_all_models():
    """Get list of all available models from database (without sensitive info for frontend)"""
    try:
        models = get_all_ai_models(active_only=True)
        
        # Return models without API keys for security
        return [
            {
                "name": m["name"],
                "description": m["description"],
                "tier": m["tier"],
                "provider": m["provider"],
                "status": m["status"],
                "capabilities": m["capabilities"],
                "max_tokens": m["max_tokens"],
                "auth_required": m["auth_required"]
            }
            for m in models
        ]
    except Exception as e:
        print(f"Error loading models from database: {e}")
        return []


def get_no_auth_models():
    """Get models that require absolutely no authentication from database"""
    try:
        all_models = get_all_ai_models(active_only=True)
        return [m for m in all_models if not m.get("auth_required", False)]
    except:
        return []


def get_minimal_auth_models():
    """Get models that require minimal signup but offer free tiers from database"""
    try:
        all_models = get_all_ai_models(active_only=True)
        return [m for m in all_models if m.get("auth_required", False)]
    except:
        return []


def get_models_by_provider(provider_name: str):
    """Get models filtered by provider from database"""
    try:
        return get_ai_models_by_provider(provider_name)
    except:
        return []


def get_models_by_capability(capability: str):
    """Get models filtered by capability from database"""
    try:
        return get_ai_models_by_capability(capability)
    except:
        return []


def get_coding_models():
    """Get models specifically good for coding from database"""
    return get_models_by_capability("code")


def get_vision_models():
    """Get models that support vision/image processing from database"""
    return get_models_by_capability("vision")


def get_image_generation_models():
    """Get models for image generation from database"""
    return get_models_by_capability("image")


def get_provider_stats():
    """Get comprehensive provider statistics from database"""
    try:
        all_models = get_all_ai_models(active_only=True)
        no_auth = len([m for m in all_models if not m.get("auth_required", False)])
        minimal_auth = len([m for m in all_models if m.get("auth_required", False)])
        
        providers = {}
        for model in all_models:
            provider = model["provider"]
            if provider not in providers:
                providers[provider] = {
                    "count": 0, 
                    "models": [], 
                    "capabilities": set(),
                    "auth_required": model["auth_required"]
                }
            providers[provider]["count"] += 1
            providers[provider]["models"].append(model["name"])
            providers[provider]["capabilities"].update(model["capabilities"])
        
        return {
            "total_models": len(all_models),
            "no_auth_models": no_auth,
            "minimal_auth_models": minimal_auth,
            "providers": {k: {**v, "capabilities": list(v["capabilities"])} for k, v in providers.items()}
        }
    except Exception as e:
        print(f"Error getting provider stats: {e}")
        return {
            "total_models": 0,
            "no_auth_models": 0,
            "minimal_auth_models": 0,
            "providers": {}
        }


def get_recommended_models():
    """Get recommended models for different use cases"""
    try:
        all_models = get_all_ai_models(active_only=True)
        
        # Get models by capability
        text_models = [m['name'] for m in all_models if 'text' in m.get('capabilities', [])]
        code_models = [m['name'] for m in all_models if 'code' in m.get('capabilities', [])]
        vision_models = [m['name'] for m in all_models if 'vision' in m.get('capabilities', [])]
        
        return {
            "general_purpose": text_models[:4] if text_models else ['geminisearch'],
            "coding": code_models[:4] if code_models else ['geminisearch'],
            "vision": vision_models[:4] if vision_models else ['geminisearch'],
            "fast_inference": text_models[:4] if text_models else ['geminisearch'],
        }
    except:
        return {
            "general_purpose": ['geminisearch'],
            "coding": ['geminisearch'],
            "vision": ['geminisearch'],
            "fast_inference": ['geminisearch'],
        }


# Print configuration status on module load
print("=" * 70)
print("AI Models Configuration System - Database Mode")
print("=" * 70)
print("🔧 Models are loaded from database dynamically")
print("📦 To migrate models from GitHub, run:")
print("   python aimodel_selector/migrate_models_to_db.py")
print("=" * 70)
