"""
Database Initialization Script for MHA Flow v3.0
Sets up the database and creates default data
Supports PostgreSQL, MySQL, and SQLite
"""
import os
import sys

# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app_production import app, db
from models import User, SystemSettings
from config import get_config


def init_database():
    """Initialize database tables"""
    print("\n" + "="*70)
    print("MHA Flow Database Initialization")
    print("="*70)
    
    # Show database type
    db_uri = app.config['SQLALCHEMY_DATABASE_URI']
    if 'postgresql' in db_uri:
        db_type = "PostgreSQL (Cloud Database)"
    elif 'mysql' in db_uri:
        db_type = "MySQL (Cloud Database)"
    else:
        db_type = "SQLite (Local Development)"
    
    print(f"\n📊 Database Type: {db_type}")
    print(f"📍 Environment: {os.environ.get('FLASK_ENV', 'development')}")
    
    print("\n🔧 Creating database tables...")
    with app.app_context():
        try:
            db.create_all()
            print("✅ Database tables created successfully")
            return True
        except Exception as e:
            print(f"❌ Error creating tables: {e}")
            return False


def create_admin_user(username='admin', email='admin@mhaflow.com', password='admin123'):
    """Create default admin user"""
    print(f"\nCreating admin user '{username}'...")
    with app.app_context():
        # Check if admin exists
        existing_user = User.query.filter_by(username=username).first()
        if existing_user:
            print(f"⚠ User '{username}' already exists")
            return False
        
        # Create admin
        admin = User(
            username=username,
            email=email,
            is_admin=True,
            is_active=True
        )
        admin.set_password(password)
        
        db.session.add(admin)
        db.session.commit()
        
        print(f"✓ Admin user created successfully")
        print(f"  Username: {username}")
        print(f"  Email: {email}")
        print(f"  Password: {password}")
        print(f"  ⚠ IMPORTANT: Change the default password after first login!")
        return True


def create_demo_user(username='demo', email='demo@mhaflow.com', password='demo123'):
    """Create demo user"""
    print(f"\nCreating demo user '{username}'...")
    with app.app_context():
        # Check if user exists
        existing_user = User.query.filter_by(username=username).first()
        if existing_user:
            print(f"⚠ User '{username}' already exists")
            # Update password to ensure it works
            existing_user.set_password(password)
            existing_user.is_active = True
            db.session.commit()
            print(f"✓ Demo user password updated")
            return True
        
        # Create demo user
        demo = User(
            username=username,
            email=email,
            is_admin=False,
            is_active=True
        )
        demo.set_password(password)
        
        db.session.add(demo)
        db.session.commit()
        
        print(f"✓ Demo user created successfully")
        print(f"  Username: {username}")
        print(f"  Email: {email}")
        print(f"  Password: {password}")
        return True


def init_system_settings():
    """Initialize system settings"""
    print("\nInitializing system settings...")
    with app.app_context():
        settings = [
            ('max_upload_size', '16777216', 'Maximum file upload size in bytes (16MB)'),
            ('max_algorithms_per_user', '50', 'Maximum custom algorithms per user'),
            ('max_concurrent_optimizations', '5', 'Maximum concurrent optimizations'),
            ('default_population_size', '30', 'Default population size'),
            ('default_max_iterations', '100', 'Default maximum iterations'),
            ('enable_levy_flight', 'true', 'Enable Levy flight by default'),
            ('maintenance_mode', 'false', 'Maintenance mode flag'),
        ]
        
        for key, value, description in settings:
            existing = SystemSettings.query.filter_by(key=key).first()
            if not existing:
                setting = SystemSettings(key=key, value=value, description=description)
                db.session.add(setting)
        
        db.session.commit()
        print(f"✓ System settings initialized ({len(settings)} settings)")


def reset_database():
    """Reset database (WARNING: Deletes all data)"""
    print("\n⚠ WARNING: This will delete all data!")
    confirm = input("Type 'yes' to confirm: ")
    
    if confirm.lower() != 'yes':
        print("Database reset cancelled")
        return
    
    print("\nResetting database...")
    with app.app_context():
        db.drop_all()
        print("✓ All tables dropped")
        
        db.create_all()
        print("✓ Fresh database created")


def show_stats():
    """Show database statistics"""
    print("\nDatabase Statistics:")
    print("=" * 50)
    with app.app_context():
        total_users = User.query.count()
        active_users = User.query.filter_by(is_active=True).count()
        admin_users = User.query.filter_by(is_admin=True).count()
        
        print(f"Total Users: {total_users}")
        print(f"Active Users: {active_users}")
        print(f"Admin Users: {admin_users}")
        
        from models import OptimizationResult, CustomAlgorithm, ComparisonSession
        
        total_optimizations = OptimizationResult.query.count()
        total_custom_algos = CustomAlgorithm.query.count()
        total_comparisons = ComparisonSession.query.count()
        
        print(f"\nOptimization Results: {total_optimizations}")
        print(f"Custom Algorithms: {total_custom_algos}")
        print(f"Comparison Sessions: {total_comparisons}")


def main():
    """Main initialization function"""
    print("\n" + "=" * 80)
    print("MHA FLOW v3.0 - DATABASE INITIALIZATION")
    print("=" * 80 + "\n")
    
    if len(sys.argv) > 1:
        command = sys.argv[1].lower()
        
        if command == 'init':
            init_database()
            init_system_settings()
            print("\n✓ Database initialized successfully!")
            
        elif command == 'admin':
            username = sys.argv[2] if len(sys.argv) > 2 else 'admin'
            email = sys.argv[3] if len(sys.argv) > 3 else 'admin@mhaflow.com'
            password = sys.argv[4] if len(sys.argv) > 4 else 'admin123'
            create_admin_user(username, email, password)
            
        elif command == 'demo':
            create_demo_user()
            
        elif command == 'reset':
            reset_database()
            init_system_settings()
            
        elif command == 'stats':
            show_stats()
            
        elif command == 'full':
            # Full setup
            init_database()
            init_system_settings()
            create_admin_user()
            create_demo_user()
            print("\n" + "=" * 80)
            print("✓ FULL SETUP COMPLETE")
            print("=" * 80)
            print("\nDefault Accounts Created:")
            print("  Admin - Username: admin, Password: admin123")
            print("  Demo  - Username: demo,  Password: demo123")
            print("\n⚠ Change default passwords after first login!")
            
        else:
            print(f"Unknown command: {command}")
            print_usage()
    else:
        print_usage()


def print_usage():
    """Print usage instructions"""
    print("Usage:")
    print("  python init_db.py init              - Initialize database tables")
    print("  python init_db.py admin [user] [email] [pass] - Create admin user")
    print("  python init_db.py demo              - Create demo user")
    print("  python init_db.py reset             - Reset database (WARNING: Deletes all data)")
    print("  python init_db.py stats             - Show database statistics")
    print("  python init_db.py full              - Full setup (init + admin + demo)")
    print("\nExamples:")
    print("  python init_db.py full")
    print("  python init_db.py admin myuser user@example.com mypassword")


if __name__ == '__main__':
    main()
