#!/usr/bin/env python
"""
Development startup script for Dubai Analytics Platform
"""
import os
import sys
import subprocess
import time

def check_database_connection():
    """Check if PostgreSQL database is accessible"""
    try:
        import psycopg2
        conn = psycopg2.connect(
            host='localhost',
            port='5432',
            database='data_analysis',
            user='postgres',
            password='Admin@123'
        )
        conn.close()
        return True
    except Exception as e:
        print(f"❌ Database connection failed: {e}")
        return False

def install_requirements():
    """Install Python requirements"""
    print("📦 Installing Python requirements...")
    try:
        subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'], check=True)
        print("✅ Requirements installed")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to install requirements: {e}")
        return False

def run_migrations():
    """Run Django migrations"""
    print("📊 Running database migrations...")
    try:
        subprocess.run([sys.executable, 'manage.py', 'migrate'], check=True)
        print("✅ Migrations completed")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Migrations failed: {e}")
        return False

def create_superuser():
    """Create superuser if it doesn't exist"""
    print("👤 Checking superuser...")
    try:
        # Check if superuser exists
        result = subprocess.run([
            sys.executable, 'manage.py', 'shell', '-c',
            "from django.contrib.auth import get_user_model; User = get_user_model(); print('EXISTS' if User.objects.filter(is_superuser=True).exists() else 'NOT_EXISTS')"
        ], capture_output=True, text=True)
        
        if 'NOT_EXISTS' in result.stdout:
            print("Creating superuser...")
            subprocess.run([
                sys.executable, 'manage.py', 'createsuperuser',
                '--username', 'admin',
                '--email', 'admin@dubai-analytics.com',
                '--noinput'
            ], check=True)
            # Set password
            subprocess.run([
                sys.executable, 'manage.py', 'shell', '-c',
                "from django.contrib.auth import get_user_model; User = get_user_model(); u = User.objects.get(username='admin'); u.set_password('admin123'); u.save()"
            ], check=True)
            print("✅ Superuser created: admin@dubai-analytics.com / admin123")
        else:
            print("✅ Superuser already exists")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Superuser creation failed: {e}")
        return False

def import_sample_data():
    """Import sample data if available"""
    if os.path.exists('sample data'):
        print("📁 Importing sample data...")
        try:
            subprocess.run([
                sys.executable, 'manage.py', 'import_csv_data',
                '--data-dir', 'sample data'
            ], check=True)
            print("✅ Sample data imported")
        except subprocess.CalledProcessError as e:
            print(f"⚠️  Sample data import failed: {e}")
    else:
        print("⚠️  Sample data directory not found, skipping import")

def start_server():
    """Start Django development server"""
    print("🚀 Starting Django development server...")
    print("📍 Backend API: http://localhost:8000")
    print("📍 API Docs: http://localhost:8000/api/docs/")
    print("📍 Admin: http://localhost:8000/admin/")
    print("\nPress Ctrl+C to stop the server")
    
    try:
        subprocess.run([sys.executable, 'manage.py', 'runserver', '0.0.0.0:8000'])
    except KeyboardInterrupt:
        print("\n👋 Server stopped")

def main():
    print("=" * 50)
    print("  Dubai Analytics Platform - Development Setup")
    print("=" * 50)
    print()
    
    # Check database connection
    if not check_database_connection():
        print("❌ Please ensure PostgreSQL is running and accessible")
        print("   Database: data_analysis")
        print("   User: postgres")
        print("   Password: Admin@123")
        print("   Host: localhost:5432")
        return
    
    print("✅ Database connection successful")
    
    # Install requirements
    if not install_requirements():
        return
    
    # Run migrations
    if not run_migrations():
        return
    
    # Create superuser
    if not create_superuser():
        return
    
    # Import sample data
    import_sample_data()
    
    print("\n🎉 Setup completed successfully!")
    print("\nNext steps:")
    print("1. Start the frontend: cd frontend && npm install && npm run dev")
    print("2. Access the admin panel: http://localhost:3000")
    print("3. Login with: admin@dubai-analytics.com / admin123")
    print()
    
    # Start server
    start_server()

if __name__ == '__main__':
    main()
