"""
AI Models Database Manager (SQLAlchemy Version)
Handles all database operations for AI model configurations in Ashlya Academy Admin
"""

import json
import logging

# Import SQLAlchemy model and db session
from models.ai import AIModel
from config import db

logger = logging.getLogger(__name__)

def get_all_ai_models(active_only=True):
    """Get all AI models from database"""
    try:
        query = AIModel.query
        if active_only:
            query = query.filter(AIModel.status.in_(['active', 'working']))
        
        models = query.order_by(AIModel.name).all()
        
        result = []
        for model in models:
            model_dict = model.to_dict()
            # The model already returns capabilities as JSON array/dict if configured right, 
            # but we parse it if it comes out as string
            if isinstance(model_dict.get('capabilities'), str):
                try:
                    model_dict['capabilities'] = json.loads(model_dict['capabilities'])
                except:
                    model_dict['capabilities'] = []
            elif not model_dict.get('capabilities'):
                model_dict['capabilities'] = []
                
            result.append(model_dict)
            
        return result
    except Exception as e:
        logger.error(f"Error fetching AI models: {e}")
        return []

def get_ai_model_by_name(model_name):
    """Get a specific AI model by name"""
    try:
        model = AIModel.query.filter_by(name=model_name).first()
        if not model:
            return None
            
        model_dict = model.to_dict()
        if isinstance(model_dict.get('capabilities'), str):
            try:
                model_dict['capabilities'] = json.loads(model_dict['capabilities'])
            except:
                model_dict['capabilities'] = []
        elif not model_dict.get('capabilities'):
            model_dict['capabilities'] = []
                
        return model_dict
    except Exception as e:
        logger.error(f"Error fetching AI model {model_name}: {e}")
        return None

def get_ai_model_by_id(model_id):
    """Get a specific AI model by ID"""
    try:
        model = AIModel.query.get(model_id)
        if not model:
            return None
            
        model_dict = model.to_dict()
        if isinstance(model_dict.get('capabilities'), str):
            try:
                model_dict['capabilities'] = json.loads(model_dict['capabilities'])
            except:
                model_dict['capabilities'] = []
        elif not model_dict.get('capabilities'):
            model_dict['capabilities'] = []
            
        return model_dict
    except Exception as e:
        logger.error(f"Error fetching AI model ID {model_id}: {e}")
        return None

def get_ai_models_by_provider(provider_name):
    """Get all models from a specific provider"""
    try:
        models = AIModel.query.filter(
            AIModel.provider == provider_name,
            AIModel.status.in_(['active', 'working'])
        ).order_by(AIModel.name).all()
        
        result = []
        for model in models:
            model_dict = model.to_dict()
            if isinstance(model_dict.get('capabilities'), str):
                try:
                    model_dict['capabilities'] = json.loads(model_dict['capabilities'])
                except:
                    model_dict['capabilities'] = []
            elif not model_dict.get('capabilities'):
                model_dict['capabilities'] = []
            result.append(model_dict)
            
        return result
    except Exception as e:
        logger.error(f"Error fetching models by provider {provider_name}: {e}")
        return []

def get_ai_models_by_capability(capability):
    """Get all models with a specific capability"""
    try:
        # Since capabilities is JSON, we might need a simpler filter or a full fetch if DB doesn't support JSON_CONTAINS well via SQLAlchemy
        # Doing simple python filter for safety/compatibility
        models = AIModel.query.filter(AIModel.status.in_(['active', 'working'])).all()
        
        result = []
        for model in models:
            model_dict = model.to_dict()
            caps = []
            
            if isinstance(model_dict.get('capabilities'), str):
                try:
                    caps = json.loads(model_dict['capabilities'])
                except:
                    caps = []
            elif model_dict.get('capabilities'):
                caps = model_dict['capabilities']
                
            model_dict['capabilities'] = caps
            
            if capability in caps:
                result.append(model_dict)
                
        # Sort by name
        result.sort(key=lambda x: x['name'])
        return result
    except Exception as e:
        logger.error(f"Error fetching models by capability {capability}: {e}")
        return []

def create_ai_model(name, description, tier, model, provider, api_key=None, base_url=None, 
                   status='active', capabilities=None, max_tokens=8192, auth_required=False,
                   is_free=False):
    """Create a new AI model in the database"""
    try:
        new_model = AIModel(
            name=name,
            description=description,
            tier=tier,
            model=model,
            provider=provider,
            api_key=api_key,
            base_url=base_url,
            status=status,
            capabilities=capabilities,
            max_tokens=max_tokens,
            auth_required=auth_required,
            is_free=is_free
        )
        db.session.add(new_model)
        db.session.commit()
        
        logger.info(f"Created AI model: {name} (ID: {new_model.id})")
        return new_model.id
    except Exception as e:
        logger.error(f"Error creating AI model {name}: {e}")
        db.session.rollback()
        return None

def update_ai_model(model_id, **kwargs):
    """Update an AI model"""
    try:
        model = AIModel.query.get(model_id)
        if not model:
            return False
            
        allowed_fields = ['name', 'description', 'tier', 'model', 'provider', 'api_key', 
                         'base_url', 'status', 'capabilities', 'max_tokens', 'auth_required',
                         'is_free']
        
        updated = False
        for field, value in kwargs.items():
            if field in allowed_fields:
                setattr(model, field, value)
                updated = True
                
        if updated:
            db.session.commit()
            logger.info(f"Updated AI model ID: {model_id}")
            return True
            
        return False
    except Exception as e:
        logger.error(f"Error updating AI model {model_id}: {e}")
        db.session.rollback()
        return False

def delete_ai_model(model_id):
    """Delete an AI model (soft delete - mark as inactive)"""
    try:
        model = AIModel.query.get(model_id)
        if not model:
            return False
            
        model.status = 'inactive'
        db.session.commit()
        
        logger.info(f"Deleted/deactivated AI model ID: {model_id}")
        return True
    except Exception as e:
        logger.error(f"Error deleting AI model {model_id}: {e}")
        db.session.rollback()
        return False

def get_provider_list():
    """Get list of all unique providers"""
    try:
        providers = db.session.query(AIModel.provider).filter(
            AIModel.status.in_(['active', 'working'])
        ).distinct().order_by(AIModel.provider).all()
        
        return [p[0] for p in providers if p[0]]
    except Exception as e:
        logger.error(f"Error fetching provider list: {e}")
        return []
