#!/usr/bin/env python
"""
Database setup script for Dubai Analytics Platform
"""
import os
import sys
import django
from django.core.management import execute_from_command_line

# Add the project directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Set Django settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dubai_analytics.settings')

# Setup Django
django.setup()

def setup_database():
    """Setup the database with migrations and sample data"""
    print("🚀 Setting up Dubai Analytics Database...")
    
    # Run migrations
    print("📊 Running database migrations...")
    execute_from_command_line(['manage.py', 'migrate'])
    
    # Create superuser if it doesn't exist
    print("👤 Creating superuser...")
    from django.contrib.auth import get_user_model
    User = get_user_model()
    
    if not User.objects.filter(is_superuser=True).exists():
        User.objects.create_superuser(
            username='admin',
            email='admin@dubai-analytics.com',
            password='admin123'
        )
        print("✅ Superuser created: admin@dubai-analytics.com / admin123")
    else:
        print("✅ Superuser already exists")
    
    # Import sample data
    print("📁 Importing sample data...")
    try:
        execute_from_command_line(['manage.py', 'import_csv_data', '--data-dir', 'sample data'])
        print("✅ Sample data imported successfully")
    except Exception as e:
        print(f"⚠️  Warning: Could not import sample data: {e}")
        print("   You can import it later with: python manage.py import_csv_data --data-dir 'sample data'")
    
    print("🎉 Database setup completed!")
    print("\nNext steps:")
    print("1. Start the backend: python manage.py runserver")
    print("2. Start the frontend: cd frontend && npm run dev")
    print("3. Access admin panel: http://localhost:3000")
    print("4. Access API docs: http://localhost:8000/api/docs/")

if __name__ == '__main__':
    setup_database()
