"""
Management command to check and apply migrations
Useful for production environments where SSH access is limited
"""

from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.db import connection
from django.db.migrations.executor import MigrationExecutor


class Command(BaseCommand):
    help = 'Check migration status and optionally apply them'

    def add_arguments(self, parser):
        parser.add_argument(
            '--apply',
            action='store_true',
            help='Apply pending migrations',
        )

    def handle(self, *args, **options):
        self.stdout.write("=" * 60)
        self.stdout.write(self.style.WARNING('🔍 Checking Migration Status'))
        self.stdout.write("=" * 60)

        # Check if migrations are needed
        executor = MigrationExecutor(connection)
        plan = executor.migration_plan(executor.loader.graph.leaf_nodes())

        if not plan:
            self.stdout.write(self.style.SUCCESS('\n✅ All migrations are up to date!'))
            self.stdout.write('\n' + "=" * 60)
            return

        # Show pending migrations
        self.stdout.write(self.style.WARNING(f'\n⚠️  Found {len(plan)} pending migration(s):'))
        for migration, backwards in plan:
            app_label = migration.app_label
            migration_name = migration.name
            status_symbol = '➖' if backwards else '➕'
            self.stdout.write(f'   {status_symbol} {app_label}.{migration_name}')

        # Check if tables exist
        self.stdout.write('\n📊 Checking tables...')
        with connection.cursor() as cursor:
            cursor.execute("""
                SELECT name FROM sqlite_master 
                WHERE type='table' AND name LIKE 'appsponsor_%'
            """ if 'sqlite' in connection.settings_dict['ENGINE'] else """
                SHOW TABLES LIKE 'appsponsor_%'
            """)
            existing_tables = [row[0] for row in cursor.fetchall()]
            
            if existing_tables:
                self.stdout.write(f'   Found {len(existing_tables)} appsponsor table(s):')
                for table in existing_tables:
                    self.stdout.write(f'   ✓ {table}')
            else:
                self.stdout.write(self.style.ERROR('   ❌ No appsponsor tables found!'))

        # Apply migrations if requested
        if options['apply']:
            self.stdout.write('\n' + "=" * 60)
            self.stdout.write(self.style.WARNING('🚀 Applying Migrations...'))
            self.stdout.write("=" * 60 + '\n')
            
            try:
                call_command('migrate', verbosity=2)
                self.stdout.write('\n' + self.style.SUCCESS('✅ Migrations applied successfully!'))
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'\n❌ Migration failed: {str(e)}'))
                raise
        else:
            self.stdout.write('\n' + "=" * 60)
            self.stdout.write(self.style.WARNING('💡 To apply these migrations, run:'))
            self.stdout.write(self.style.SUCCESS('   python manage.py check_migrations --apply'))
            self.stdout.write("   OR")
            self.stdout.write(self.style.SUCCESS('   python manage.py migrate'))

        self.stdout.write('\n' + "=" * 60)
