"""
Django management command to create aws-admin account and move developer/super admin users to it
Usage: python manage.py create_aws_admin_account
"""
from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import Q
from django.utils.text import slugify
from igny8_core.auth.models import Account, User, Plan


class Command(BaseCommand):
    help = 'Create aws-admin account and move developer/super admin users to it'

    def handle(self, *args, **options):
        with transaction.atomic():
            # Step 1: Get or create an Enterprise plan for the aws-admin account
            # System accounts should have unlimited access via Enterprise plan
            plan, created = Plan.objects.get_or_create(
                slug='enterprise',
                defaults={
                    'name': 'Enterprise Plan',
                    'price': 0.00,
                    'billing_cycle': 'monthly',
                    'max_users': 999999,
                    'max_sites': 999999,
                    'max_keywords': 999999,
                    'max_clusters': 999999,
                    'max_content_ideas': 999999,
                    'monthly_word_count_limit': 999999999,
                    'daily_content_tasks': 999999,
                    'daily_ai_requests': 999999,
                    'daily_ai_request_limit': 999999,
                    'monthly_ai_credit_limit': 999999,
                    'monthly_image_count': 999999,
                    'daily_image_generation_limit': 999999,
                    'monthly_cluster_ai_credits': 999999,
                    'monthly_content_ai_credits': 999999,
                    'monthly_image_ai_credits': 999999,
                    'included_credits': 999999,
                    'is_active': True,
                    'features': ['ai_writer', 'image_gen', 'auto_publish', 'custom_prompts', 'unlimited'],
                }
            )
            if created:
                self.stdout.write(self.style.SUCCESS(f'✅ Created Enterprise plan: {plan.name}'))
            else:
                self.stdout.write(f'Using existing Enterprise plan: {plan.name}')

            # Step 2: Get the first superuser or developer to be the owner
            # If no superuser exists, we'll need to create one or use the first user
            owner = User.objects.filter(
                Q(is_superuser=True) | Q(role='developer')
            ).first()
            
            if not owner:
                # Try to get any user
                owner = User.objects.first()
                if not owner:
                    self.stdout.write(self.style.ERROR('No users found. Please create a user first.'))
                    return
                self.stdout.write(self.style.WARNING(f'No superuser/developer found. Using first user as owner: {owner.username}'))
            else:
                self.stdout.write(f'Using owner: {owner.username} (ID: {owner.id})')

            # Step 3: Create or get aws-admin account
            account, created = Account.objects.get_or_create(
                slug='aws-admin',
                defaults={
                    'name': 'AWS Admin',
                    'owner': owner,
                    'plan': plan,
                    'credits': 999999,
                    'status': 'active',
                }
            )
            
            # Always ensure aws-admin account uses Enterprise plan (update if needed)
            if account.plan != plan:
                old_plan_name = account.plan.name if account.plan else 'None'
                account.plan = plan
                account.save()
                self.stdout.write(self.style.SUCCESS(f'✅ Updated account plan from "{old_plan_name}" to "{plan.name}"'))
            
            if created:
                self.stdout.write(self.style.SUCCESS(f'✅ Created account: {account.name} (slug: {account.slug})'))
            else:
                self.stdout.write(f'Account "{account.name}" already exists, using existing one.')

            # Step 4: Find all developer and super admin users
            developer_users = User.objects.filter(
                Q(role='developer') | Q(is_superuser=True)
            ).distinct()
            
            moved_count = 0
            skipped_count = 0
            
            for user in developer_users:
                if user.account == account:
                    skipped_count += 1
                    self.stdout.write(f'  - User {user.username} ({user.email}) already in aws-admin account, skipping...')
                    continue
                
                old_account = user.account
                user.account = account
                user.save()
                moved_count += 1
                
                old_account_name = old_account.name if old_account else 'None'
                self.stdout.write(
                    self.style.SUCCESS(
                        f'  ✅ Moved user {user.username} ({user.email}) from "{old_account_name}" to "{account.name}"'
                    )
                )

            # Summary
            self.stdout.write('')
            self.stdout.write(self.style.SUCCESS('=' * 60))
            self.stdout.write(self.style.SUCCESS('Summary:'))
            self.stdout.write(f'  - Account: {account.name} (slug: {account.slug})')
            self.stdout.write(f'  - Users moved: {moved_count}')
            self.stdout.write(f'  - Users already in account: {skipped_count}')
            self.stdout.write(f'  - Total developer/super admin users: {developer_users.count()}')
            self.stdout.write(self.style.SUCCESS('=' * 60))
            self.stdout.write('')
            self.stdout.write(
                self.style.SUCCESS(
                    '✅ All developer and super admin users have been moved to the aws-admin account.'
                )
            )
            self.stdout.write(
                '   These users now have access to all data across all accounts without filtering.'
            )

