"""
Database Helper Functions
SQLite database abstraction layer for MHA Flow
"""
from models import db, User, OptimizationResult, CustomAlgorithm, ComparisonSession
from sqlalchemy import desc


def get_user_by_id(user_id):
    """Get user by ID"""
    return User.query.get(int(user_id))


def get_user_by_username(username):
    """Get user by username"""
    return User.query.filter_by(username=username).first()


def get_user_by_email(email):
    """Get user by email"""
    return User.query.filter_by(email=email).first()


def count_users():
    """Count total users"""
    return User.query.count()


def save_object(obj):
    """Save object to database"""
    try:
        db.session.add(obj)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        raise e


def delete_object(obj):
    """Delete object from database"""
    try:
        db.session.delete(obj)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        raise e


def rollback():
    """Rollback transaction"""
    db.session.rollback()


def get_optimization_result_by_id(result_id):
    """Get optimization result by ID"""
    return OptimizationResult.query.get(result_id)


def get_user_optimization_results(user_id, limit=None, order_by='created_at'):
    """Get user's optimization results"""
    query = OptimizationResult.query.filter_by(user_id=user_id)
    if order_by:
        column = getattr(OptimizationResult, order_by, OptimizationResult.created_at)
        query = query.order_by(desc(column))
    if limit:
        query = query.limit(limit)
    return query.all()


def get_user_custom_algorithms(user_id, limit=None):
    """Get user's custom algorithms"""
    query = CustomAlgorithm.query.filter_by(user_id=user_id).order_by(desc(CustomAlgorithm.upload_date))
    if limit:
        query = query.limit(limit)
    return query.all()


def count_user_optimizations(user_id):
    """Count user's optimizations"""
    return OptimizationResult.query.filter_by(user_id=user_id).count()


def count_user_custom_algos(user_id):
    """Count user's custom algorithms"""
    return CustomAlgorithm.query.filter_by(user_id=user_id).count()


def count_user_comparisons(user_id):
    """Count user's comparison sessions"""
    return ComparisonSession.query.filter_by(user_id=user_id).count()


def get_best_result(user_id, order_by='best_fitness'):
    """Get best optimization result"""
    column = getattr(OptimizationResult, order_by, OptimizationResult.best_fitness)
    return OptimizationResult.query.filter_by(user_id=user_id).order_by(column).first()


def count_successful_runs(user_id):
    """Count successful optimization runs"""
    return OptimizationResult.query.filter_by(user_id=user_id, status='completed').count()


def get_all_completed_results(user_id):
    """Get all completed optimization results"""
    return OptimizationResult.query.filter_by(user_id=user_id, status='completed').all()


def get_user_id_for_mongodb(user_id):
    """Get user ID (compatibility function)"""
    return user_id
