"""
Django management command to create default expense categories for all businesses

Usage:
    python manage.py create_expense_categories
    python manage.py create_expense_categories --business-id=<uuid>
"""

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from apps.sales.models import ExpenseCategory
from apps.business.models import Business


class Command(BaseCommand):
    help = 'Create default expense categories for businesses'

    def add_arguments(self, parser):
        parser.add_argument(
            '--business-id',
            type=str,
            help='Specific business ID to create categories for (optional)',
        )
        parser.add_argument(
            '--force',
            action='store_true',
            help='Force creation even if categories already exist',
        )

    def handle(self, *args, **options):
        business_id = options.get('business_id')
        force = options.get('force', False)

        # Default categories
        categories = [
            {'name': 'Rent', 'description': 'Office/Shop rent payments'},
            {'name': 'Utilities', 'description': 'Electricity, water, internet'},
            {'name': 'Salaries', 'description': 'Employee salaries and wages'},
            {'name': 'Inventory', 'description': 'Stock purchases'},
            {'name': 'Marketing', 'description': 'Advertising and promotions'},
            {'name': 'Transport', 'description': 'Delivery and transport costs'},
            {'name': 'Maintenance', 'description': 'Equipment and facility maintenance'},
            {'name': 'Office Supplies', 'description': 'Stationery and office materials'},
            {'name': 'Insurance', 'description': 'Business insurance premiums'},
            {'name': 'Professional Services', 'description': 'Legal, accounting, consulting'},
            {'name': 'Broker', 'description': 'Broker fees and commissions'},
            {'name': 'Miscellaneous', 'description': 'Other business expenses'},
        ]

        # Get businesses to process
        if business_id:
            try:
                businesses = [Business.objects.get(id=business_id)]
                self.stdout.write(
                    self.style.SUCCESS(
                        f'Processing specific business: {businesses[0].name}'
                    )
                )
            except Business.DoesNotExist:
                raise CommandError(f'Business with ID "{business_id}" does not exist')
        else:
            businesses = Business.objects.all()
            self.stdout.write(
                self.style.SUCCESS(
                    f'Processing all businesses ({businesses.count()} total)'
                )
            )

        # Statistics
        total_created = 0
        total_skipped = 0
        total_updated = 0

        # Process each business
        for business in businesses:
            self.stdout.write(f'\nProcessing business: {business.name}')

            # Check if categories already exist
            existing_count = ExpenseCategory.objects.filter(business=business).count()

            if existing_count > 0 and not force:
                self.stdout.write(
                    self.style.WARNING(
                        f'  Skipping - {existing_count} categories already exist. '
                        f'Use --force to recreate.'
                    )
                )
                total_skipped += existing_count
                continue

            # Create categories in a transaction
            with transaction.atomic():
                for cat_data in categories:
                    category, created = ExpenseCategory.objects.get_or_create(
                        business=business,
                        name=cat_data['name'],
                        defaults={
                            'description': cat_data['description'],
                            'is_active': True
                        }
                    )

                    if created:
                        self.stdout.write(
                            self.style.SUCCESS(
                                f'  [CREATED] {category.name}'
                            )
                        )
                        total_created += 1
                    else:
                        # Update description if it exists
                        if category.description != cat_data['description']:
                            category.description = cat_data['description']
                            category.save()
                            self.stdout.write(
                                self.style.WARNING(
                                    f'  [UPDATED] {category.name}'
                                )
                            )
                            total_updated += 1
                        else:
                            self.stdout.write(
                                f'  [EXISTS] {category.name}'
                            )
                            total_skipped += 1

        # Summary
        self.stdout.write('\n' + '=' * 60)
        self.stdout.write(self.style.SUCCESS('\nSummary:'))
        self.stdout.write(f'  Categories created: {total_created}')
        self.stdout.write(f'  Categories updated: {total_updated}')
        self.stdout.write(f'  Categories skipped: {total_skipped}')
        self.stdout.write(f'  Total processed: {total_created + total_updated + total_skipped}')
        self.stdout.write('=' * 60 + '\n')

        if total_created > 0 or total_updated > 0:
            self.stdout.write(
                self.style.SUCCESS(
                    'SUCCESS: Expense categories setup completed successfully!'
                )
            )
        else:
            self.stdout.write(
                self.style.WARNING(
                    'WARNING: No changes were made. Use --force to recreate existing categories.'
                )
            )