from django.core.management.base import BaseCommand
from django.db import connection
from django.contrib.auth.hashers import make_password
import uuid

class Command(BaseCommand):
    help = 'Reset database and create admin user'

    def handle(self, *args, **options):
        self.stdout.write('Resetting database...')

        # Drop all tables
        with connection.cursor() as cursor:
            cursor.execute("""
                DO $$ DECLARE
                    r RECORD;
                BEGIN
                    FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema()) LOOP
                        EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';
                    END LOOP;
                END $$;
            """)

            # Reset sequences
            cursor.execute("""
                DO $$ DECLARE
                    r RECORD;
                BEGIN
                    FOR r IN (SELECT sequencename FROM pg_sequences WHERE schemaname = current_schema()) LOOP
                        EXECUTE 'ALTER SEQUENCE ' || quote_ident(r.sequencename) || ' RESTART WITH 1';
                    END LOOP;
                END $$;
            """)

        self.stdout.write('All tables dropped and sequences reset.')

        # Run migrations
        from django.core.management import call_command
        call_command('migrate')

        self.stdout.write('Migrations applied.')

        # Create superuser using raw SQL
        try:
            with connection.cursor() as cursor:
                # Create user
                user_id = str(uuid.uuid4())[:10]
                cursor.execute("""
                    INSERT INTO accounts_user (
                        username, password, email, is_superuser, is_staff, 
                        is_active, date_joined, user_id, first_name, 
                        last_name, role, is_banned, ban_reason, 
                        theme_preference
                    ) VALUES (
                        'admin', %s, 'admin@thrillwiki.com', true, true,
                        true, NOW(), %s, '', '', 'SUPERUSER', false, '',
                        'light'
                    ) RETURNING id;
                """, [make_password('admin'), user_id])
                
                user_db_id = cursor.fetchone()[0]

                # Create profile
                profile_id = str(uuid.uuid4())[:10]
                cursor.execute("""
                    INSERT INTO accounts_userprofile (
                        profile_id, display_name, pronouns, bio,
                        twitter, instagram, youtube, discord,
                        coaster_credits, dark_ride_credits,
                        flat_ride_credits, water_ride_credits,
                        user_id, avatar
                    ) VALUES (
                        %s, 'Admin', 'they/them', 'ThrillWiki Administrator',
                        '', '', '', '',
                        0, 0, 0, 0,
                        %s, ''
                    );
                """, [profile_id, user_db_id])

            self.stdout.write('Superuser created.')
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error creating superuser: {str(e)}'))
            raise

        self.stdout.write(self.style.SUCCESS('Database reset complete.'))
