"""
Django management command to populate inventory database with sample data.
"""

from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.utils import timezone
from decimal import Decimal
from datetime import timedelta
import random

from apps.inventory.models import (
    Category, Brand, InventoryItem, Accessory, Supplier,
    TransferRequest, TransferItem, InventoryBatch
)
from apps.business.models import Business, Location

User = get_user_model()


class Command(BaseCommand):
    help = 'Populate database with sample inventory data'

    def add_arguments(self, parser):
        parser.add_argument(
            '--clear',
            action='store_true',
            help='Clear existing data before populating',
        )
        parser.add_argument(
            '--items',
            type=int,
            default=50,
            help='Number of inventory items to create (default: 50)',
        )

    def handle(self, *args, **options):
        if options['clear']:
            self.stdout.write('Clearing existing data...')
            self.clear_data()

        self.stdout.write('Starting data population...')
        
        # Create data in order of dependencies
        user = self.create_user()
        business = self.create_business(user)
        locations = self.create_locations(business)
        categories = self.create_categories()
        brands = self.create_brands()
        suppliers = self.create_suppliers(business)
        
        num_items = options['items']
        inventory_items = self.create_inventory_items(
            business, locations, brands, categories, suppliers, num_items
        )
        
        self.create_accessories(business, locations, brands)
        self.create_transfers(business, locations, inventory_items, user)
        self.create_batches(business, locations, user)
        
        self.stdout.write(self.style.SUCCESS('✓ Data population completed successfully!'))
        self.print_summary(business, num_items)

    def clear_data(self):
        """Clear existing inventory data"""
        InventoryBatch.objects.all().delete()
        TransferItem.objects.all().delete()
        TransferRequest.objects.all().delete()
        Accessory.objects.all().delete()
        InventoryItem.objects.all().delete()
        Supplier.objects.all().delete()
        Brand.objects.all().delete()
        Category.objects.all().delete()
        self.stdout.write(self.style.WARNING('  Existing data cleared'))

    def create_user(self):
        """Create or get a user"""
        user, created = User.objects.get_or_create(
            username='admin',
            defaults={
                'email': 'admin@techsolutions.com',
                'is_staff': True,
                'is_superuser': True
            }
        )
        if created:
            user.set_password('admin123')
            user.save()
            self.stdout.write(self.style.SUCCESS('  ✓ Created user: admin'))
        else:
            self.stdout.write(f'  → Using existing user: {user.username}')
        return user

    def create_business(self, owner):
        """Create or get business"""
        business, created = Business.objects.get_or_create(
            name='Tech Solutions Ltd',
            defaults={
                'owner': owner,
                'email': 'info@techsolutions.com',
                'phone_number': '+254700000000',
                'address_line1': 'Nairobi, Kenya'
            }
        )
        if created:
            self.stdout.write(self.style.SUCCESS(f'  ✓ Created business: {business.name}'))
        else:
            self.stdout.write(f'  → Using existing business: {business.name}')
        return business

    def create_locations(self, business):
        """Create business locations"""
        location_data = [
            {'name': 'Main Warehouse', 'address_line1': 'Industrial Area, Nairobi'},
            {'name': 'Downtown Showroom', 'address_line1': 'CBD, Nairobi'},
            {'name': 'Westlands Branch', 'address_line1': 'Westlands, Nairobi'},
        ]
        
        locations = []
        for data in location_data:
            location, created = Location.objects.get_or_create(
                business=business,
                name=data['name'],
                defaults={'address_line1': data['address_line1']}
            )
            locations.append(location)
            if created:
                self.stdout.write(self.style.SUCCESS(f'  ✓ Created location: {location.name}'))
        
        return locations

    def create_categories(self):
        """Create product categories"""
        categories_data = [
            {'name': 'Laptops', 'description': 'Portable computers'},
            {'name': 'Desktops', 'description': 'Desktop computers'},
            {'name': 'Monitors', 'description': 'Display screens'},
            {'name': 'Accessories', 'description': 'Computer peripherals'},
            {'name': 'Components', 'description': 'Computer parts'},
        ]
        
        categories = []
        for data in categories_data:
            category, created = Category.objects.get_or_create(
                name=data['name'],
                defaults={'description': data['description']}
            )
            categories.append(category)
        
        self.stdout.write(self.style.SUCCESS(f'  ✓ Created {len(categories)} categories'))
        return categories

    def create_brands(self):
        """Create computer brands"""
        brands_data = [
            'Dell', 'HP', 'Lenovo', 'Apple', 'Asus',
            'Acer', 'Microsoft', 'Samsung', 'LG', 'MSI'
        ]
        
        brands = []
        for name in brands_data:
            brand, created = Brand.objects.get_or_create(name=name)
            brands.append(brand)
        
        self.stdout.write(self.style.SUCCESS(f'  ✓ Created {len(brands)} brands'))
        return brands

    def create_suppliers(self, business):
        """Create suppliers"""
        suppliers_data = [
            {
                'name': 'Global Tech Suppliers',
                'contact_person': 'John Doe',
                'email': 'john@globaltech.com',
                'phone': '+254700111111',
                'payment_terms': 'Net 30'
            },
            {
                'name': 'Computer Wholesale Ltd',
                'contact_person': 'Jane Smith',
                'email': 'jane@cwl.com',
                'phone': '+254700222222',
                'payment_terms': 'Net 45'
            },
            {
                'name': 'Tech Distributors Inc',
                'contact_person': 'Mike Johnson',
                'email': 'mike@techdist.com',
                'phone': '+254700333333',
                'payment_terms': 'Net 60'
            }
        ]
        
        suppliers = []
        for data in suppliers_data:
            supplier, created = Supplier.objects.get_or_create(
                business=business,
                name=data['name'],
                defaults={
                    'contact_person': data['contact_person'],
                    'email': data['email'],
                    'phone': data['phone'],
                    'payment_terms': data['payment_terms'],
                    'credit_limit': Decimal('500000.00'),
                    'rating': random.randint(3, 5)
                }
            )
            suppliers.append(supplier)
        
        self.stdout.write(self.style.SUCCESS(f'  ✓ Created {len(suppliers)} suppliers'))
        return suppliers

    def create_inventory_items(self, business, locations, brands, categories, suppliers, count):
        """Create inventory items"""
        laptop_models = ['Latitude 5420', 'ThinkPad X1', 'MacBook Pro', 'Pavilion 15', 'VivoBook']
        processors = ['Intel i5-11th Gen', 'Intel i7-12th Gen', 'AMD Ryzen 5', 'AMD Ryzen 7', 'Apple M1']
        ram_options = ['8GB', '16GB', '32GB']
        storage_options = ['256GB SSD', '512GB SSD', '1TB SSD', '1TB HDD']
        conditions = ['NEW', 'REFURBISHED', 'USED']
        statuses = ['IN_STOCK', 'IN_STOCK', 'IN_STOCK', 'SOLD', 'RESERVED']
        
        items = []
        for i in range(count):
            brand = random.choice(brands)
            category = random.choice(categories[:2])  # Laptops or Desktops
            
            # Generate unique asset_id using timestamp to avoid conflicts
            timestamp = timezone.now().strftime('%Y%m%d')
            item = InventoryItem.objects.create(
                business=business,
                asset_id=f'AST-{timestamp}-{i+1:05d}',
                brand=brand,
                model=f'{brand.name} {random.choice(laptop_models)}',
                category=category,
                condition=random.choice(conditions),
                status=random.choice(statuses),
                serial_number=f'SN{random.randint(100000, 999999)}',
                processor=random.choice(processors),
                ram=random.choice(ram_options),
                storage=random.choice(storage_options),
                screen_size='15.6"' if category.name == 'Laptops' else '',
                operating_system=random.choice(['Windows 11 Pro', 'Windows 10 Pro', 'Ubuntu 22.04']),
                location=random.choice(locations),
                quantity=random.randint(1, 10) if i % 5 != 0 else random.randint(0, 2),
                reorder_level=random.randint(3, 8),
                purchase_price=Decimal(random.randint(300, 1500)) * 100,
                selling_price=Decimal(random.randint(400, 2000)) * 100,
                supplier=random.choice(suppliers),
                purchase_date=timezone.now().date() - timedelta(days=random.randint(1, 365)),
                warranty_start_date=timezone.now().date() - timedelta(days=random.randint(1, 180)),
                warranty_end_date=timezone.now().date() + timedelta(days=random.randint(180, 730)),
                warranty_provider=random.choice(['Manufacturer', 'Third Party', 'Extended Warranty']),
                notes=f'Sample inventory item {i+1}'
            )
            items.append(item)
        
        self.stdout.write(self.style.SUCCESS(f'  ✓ Created {count} inventory items'))
        return items

    def create_accessories(self, business, locations, brands):
        """Create accessories"""
        accessories_data = [
            {'name': 'Wireless Mouse', 'category': 'Input Devices', 'sku': 'ACC-MS-001'},
            {'name': 'Mechanical Keyboard', 'category': 'Input Devices', 'sku': 'ACC-KB-001'},
            {'name': 'USB-C Hub', 'category': 'Adapters', 'sku': 'ACC-HUB-001'},
            {'name': 'Laptop Bag', 'category': 'Cases', 'sku': 'ACC-BAG-001'},
            {'name': 'HDMI Cable', 'category': 'Cables', 'sku': 'ACC-CBL-001'},
        ]
        
        for data in accessories_data:
            Accessory.objects.create(
                business=business,
                name=data['name'],
                category=data['category'],
                brand=random.choice(brands),
                location=random.choice(locations),
                quantity=random.randint(10, 100),
                reorder_level=15,
                purchase_price=Decimal(random.randint(5, 50)) * 100,
                selling_price=Decimal(random.randint(10, 80)) * 100,
                sku=data['sku']
            )
        
        self.stdout.write(self.style.SUCCESS(f'  ✓ Created {len(accessories_data)} accessories'))

    def create_transfers(self, business, locations, inventory_items, user):
        """Create transfer requests"""
        if len(locations) < 2:
            return
        
        statuses = ['PENDING', 'APPROVED', 'IN_TRANSIT', 'COMPLETED']
        
        for i in range(5):
            source = random.choice(locations)
            dest = random.choice([loc for loc in locations if loc != source])
            
            transfer = TransferRequest.objects.create(
                business=business,
                transfer_number=f'TRF-{i+1:05d}',
                source_location=source,
                destination_location=dest,
                status=random.choice(statuses),
                requested_by=user,
                approved_by=user if i > 0 else None,
                approved_date=timezone.now() - timedelta(days=random.randint(1, 10)) if i > 0 else None,
                notes=f'Sample transfer request {i+1}'
            )
            
            # Add transfer items
            num_items = random.randint(1, 3)
            selected_items = random.sample(inventory_items, min(num_items, len(inventory_items)))
            
            for item in selected_items:
                TransferItem.objects.create(
                    transfer=transfer,
                    inventory_item=item,
                    quantity=random.randint(1, 3)
                )
        
        self.stdout.write(self.style.SUCCESS('  ✓ Created 5 transfer requests'))

    def create_batches(self, business, locations, user):
        """Create inventory batches"""
        operations = ['IMPORT', 'EXPORT', 'ADJUSTMENT', 'STOCKTAKE']
        
        for i in range(3):
            InventoryBatch.objects.create(
                business=business,
                batch_number=f'BATCH-{i+1:05d}',
                operation_type=random.choice(operations),
                location=random.choice(locations),
                processed_by=user,
                total_items=random.randint(20, 100),
                successful_items=random.randint(15, 95),
                failed_items=random.randint(0, 5),
                notes=f'Sample batch operation {i+1}'
            )
        
        self.stdout.write(self.style.SUCCESS('  ✓ Created 3 batch operations'))

    def print_summary(self, business, num_items):
        """Print summary of created data"""
        self.stdout.write('\n' + '='*60)
        self.stdout.write(self.style.SUCCESS('DATA POPULATION SUMMARY'))
        self.stdout.write('='*60)
        self.stdout.write(f'Business: {business.name}')
        self.stdout.write(f'Locations: {Location.objects.filter(business=business).count()}')
        self.stdout.write(f'Categories: {Category.objects.count()}')
        self.stdout.write(f'Brands: {Brand.objects.count()}')
        self.stdout.write(f'Suppliers: {Supplier.objects.filter(business=business).count()}')
        self.stdout.write(f'Inventory Items: {InventoryItem.objects.filter(business=business).count()}')
        self.stdout.write(f'Accessories: {Accessory.objects.filter(business=business).count()}')
        self.stdout.write(f'Transfer Requests: {TransferRequest.objects.filter(business=business).count()}')
        self.stdout.write(f'Batch Operations: {InventoryBatch.objects.filter(business=business).count()}')
        self.stdout.write('='*60 + '\n')