"""
Django Management Command: Populate Business Industries
File: business/management/commands/populate_business_industries.py

This command assigns random industries and generates industry-specific 
configurations for existing businesses that don't have them set.
"""

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from apps.business.models import Business
from apps.inventory.models import Industry
import random


class Command(BaseCommand):
    help = 'Populate business industry and industry configurations for existing businesses'

    def add_arguments(self, parser):
        parser.add_argument(
            '--force',
            action='store_true',
            help='Force update even if business already has an industry',
        )
        parser.add_argument(
            '--business-id',
            type=str,
            help='Update specific business by UUID',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be updated without making changes',
        )

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

        # Get all available industries
        industries = list(Industry.objects.filter(is_active=True))
        
        if not industries:
            raise CommandError(
                'No active industries found. Please create industries first using:\n'
                'python manage.py seed_industries'
            )

        self.stdout.write(self.style.SUCCESS(f'\nFound {len(industries)} active industries:'))
        for ind in industries:
            self.stdout.write(f'  - {ind.name} ({ind.slug})')

        # Get businesses to update
        if business_id:
            businesses = Business.objects.filter(id=business_id)
            if not businesses.exists():
                raise CommandError(f'Business with ID {business_id} not found')
        elif force:
            businesses = Business.objects.all()
        else:
            businesses = Business.objects.filter(industry__isnull=True)

        total_count = businesses.count()
        
        if total_count == 0:
            self.stdout.write(self.style.WARNING(
                '\nNo businesses need updating. Use --force to update all businesses.'
            ))
            return

        self.stdout.write(self.style.WARNING(
            f'\n{"[DRY RUN] " if dry_run else ""}Found {total_count} business(es) to update\n'
        ))

        updated_count = 0
        skipped_count = 0

        with transaction.atomic():
            for business in businesses:
                # Randomly select an industry
                industry = random.choice(industries)
                
                # Generate industry-specific configuration
                config = self._generate_industry_config(industry)
                
                old_industry = business.industry.name if business.industry else 'None'
                
                self.stdout.write(
                    f'\n{"[DRY RUN] " if dry_run else ""}Business: {business.name or business.legal_name or "Unnamed"}'
                )
                self.stdout.write(f'  Current Industry: {old_industry}')
                self.stdout.write(f'  New Industry: {industry.name}')
                self.stdout.write(f'  Configuration: {config}')
                
                if not dry_run:
                    business.industry = industry
                    business.industry_configuration = config
                    business.save(update_fields=['industry', 'industry_configuration', 'updated_at'])
                    updated_count += 1
                else:
                    updated_count += 1

            if dry_run:
                self.stdout.write(self.style.WARNING(
                    f'\n[DRY RUN] Would update {updated_count} business(es)'
                ))
                # Rollback transaction in dry run
                transaction.set_rollback(True)
            else:
                self.stdout.write(self.style.SUCCESS(
                    f'\n✓ Successfully updated {updated_count} business(es)'
                ))

        # Summary
        self.stdout.write('\n' + '='*60)
        self.stdout.write(self.style.SUCCESS('Summary:'))
        self.stdout.write(f'  Total businesses processed: {total_count}')
        self.stdout.write(f'  {"Would be updated" if dry_run else "Updated"}: {updated_count}')
        if skipped_count:
            self.stdout.write(f'  Skipped: {skipped_count}')
        self.stdout.write('='*60 + '\n')

    def _generate_industry_config(self, industry):
        """Generate random but realistic industry-specific configuration"""
        
        base_config = {
            'default_unit_of_measure': industry.default_unit_of_measure,
            'tracking_requirements': {
                'serial_number': industry.requires_serial_tracking,
                'batch_number': industry.requires_batch_tracking,
                'expiry_date': industry.requires_expiry_tracking,
            },
            'workflow_enabled': True,
            'quality_control_enabled': random.choice([True, False]),
        }

        # Industry-specific configurations
        if industry.slug == 'computer-hardware':
            base_config.update({
                'warranty_tracking': True,
                'default_warranty_period_days': random.choice([365, 730, 1095]),  # 1-3 years
                'required_specs': ['processor', 'ram', 'storage'],
                'condition_tracking': True,
                'asset_depreciation': {
                    'enabled': True,
                    'method': 'straight_line',
                    'useful_life_years': random.choice([3, 4, 5]),
                },
                'repair_tracking': True,
            })
        
        elif industry.slug == 'electronics':
            base_config.update({
                'warranty_tracking': True,
                'default_warranty_period_days': random.choice([180, 365, 730]),
                'return_policy_days': random.choice([7, 14, 30]),
                'requires_testing': True,
                'testing_checklist': [
                    'Power on test',
                    'Functionality check',
                    'Physical inspection',
                ],
            })
        
        elif industry.slug == 'pharmaceuticals':
            base_config.update({
                'requires_prescription': random.choice([True, False]),
                'temperature_controlled': random.choice([True, False]),
                'expiry_alert_days': random.choice([30, 60, 90]),
                'batch_recall_enabled': True,
                'regulatory_compliance': {
                    'enabled': True,
                    'authority': random.choice(['FDA', 'PPB', 'EMA']),
                },
            })
        
        elif industry.slug == 'food-beverage':
            base_config.update({
                'allergen_tracking': True,
                'nutritional_info_required': True,
                'expiry_alert_days': random.choice([7, 14, 21]),
                'storage_requirements': {
                    'temperature_min': random.choice([-18, 0, 4, 15]),
                    'temperature_max': random.choice([4, 8, 25, 30]),
                    'humidity_controlled': random.choice([True, False]),
                },
                'halal_kosher_tracking': random.choice([True, False]),
            })
        
        elif industry.slug == 'fashion-apparel':
            base_config.update({
                'size_variants': ['XS', 'S', 'M', 'L', 'XL', 'XXL'],
                'color_variants': True,
                'seasonal_tracking': True,
                'fabric_composition_required': True,
                'care_instructions_required': True,
                'return_policy_days': random.choice([14, 30, 60]),
            })
        
        elif industry.slug == 'automotive-parts':
            base_config.update({
                'oem_compatibility_tracking': True,
                'vehicle_fitment_required': True,
                'warranty_tracking': True,
                'default_warranty_period_days': random.choice([180, 365, 730]),
                'return_policy': {
                    'days': random.choice([30, 60, 90]),
                    'core_charge': random.choice([True, False]),
                },
            })
        
        elif industry.slug == 'agriculture':
            base_config.update({
                'organic_certification': random.choice([True, False]),
                'planting_season_tracking': True,
                'harvest_date_tracking': True,
                'pesticide_usage_tracking': True,
                'weather_dependency': True,
                'storage_requirements': {
                    'humidity_controlled': True,
                    'pest_control': True,
                },
            })
        
        elif industry.slug == 'construction-materials':
            base_config.update({
                'bulk_pricing': True,
                'delivery_scheduling': True,
                'minimum_order_quantity': random.choice([10, 50, 100, 500]),
                'quality_certificates_required': True,
                'storage_location_tracking': True,
                'weather_protection_required': random.choice([True, False]),
            })
        
        elif industry.slug == 'medical-equipment':
            base_config.update({
                'calibration_tracking': True,
                'calibration_frequency_days': random.choice([90, 180, 365]),
                'sterilization_required': random.choice([True, False]),
                'regulatory_approval': {
                    'required': True,
                    'authority': random.choice(['FDA', 'CE', 'ISO']),
                },
                'maintenance_tracking': True,
                'user_training_required': random.choice([True, False]),
            })
        
        elif industry.slug == 'books-stationery':
            base_config.update({
                'isbn_tracking': True,
                'author_publisher_tracking': True,
                'edition_tracking': True,
                'language_tracking': True,
                'return_policy_days': random.choice([14, 30]),
                'bulk_discount_enabled': True,
            })

        # Add common retail settings
        base_config['pricing'] = {
            'markup_percentage': random.randint(20, 100),
            'bulk_discount_enabled': random.choice([True, False]),
            'seasonal_pricing': random.choice([True, False]),
        }

        base_config['inventory_alerts'] = {
            'low_stock_threshold': random.choice([5, 10, 20, 30]),
            'reorder_point_enabled': True,
            'expiry_alerts_enabled': industry.requires_expiry_tracking,
        }

        return base_config