"""
Generate test data for CART admin.

Creates locations, products, tags, and associations.
"""
import random
from django.contrib.auth import get_user_model
from products.models import Product, Tag, Location, LocationType


def generate_test_data(count_products=50, count_tags=200):
    """Generate test data for the CART system."""

    # Create location types
    location_types = {
        "building": LocationType.objects.get_or_create(
            name="building", defaults={"description": "Building/structure"}
        )[0],
        "warehouse": LocationType.objects.get_or_create(
            name="warehouse", defaults={"description": "Warehouse area"}
        )[0],
        "zone": LocationType.objects.get_or_create(
            name="zone", defaults={"description": "Warehouse zone"}
        )[0],
        "rack": LocationType.objects.get_or_create(
            name="rack", defaults={"description": "Storage rack"}
        )[0],
        "shelf": LocationType.objects.get_or_create(
            name="shelf", defaults={"description": "Individual shelf"}
        )[0],
        "bin": LocationType.objects.get_or_create(
            name="bin", defaults={"description": "Storage bin"}
        )[0],
    }

    # Create building locations
    buildings = []
    for i in range(3):
        building = Location.objects.get_or_create(
            code=f"BLD-{i+1:02d}",
            defaults={
                "name": f"Building {i+1}",
                "type": location_types["building"],
            }
        )[0]
        buildings.append(building)

    # Create warehouses in each building
    warehouses = []
    for building in buildings:
        for i in range(3):
            warehouse = Location.objects.get_or_create(
                code=f"{building.code}-WH{i+1:02d}",
                defaults={
                    "name": f"Warehouse {i+1}",
                    "parent": building,
                    "type": location_types["warehouse"],
                }
            )[0]
            warehouses.append(warehouse)

    # Create zones in each warehouse
    zones = []
    for warehouse in warehouses:
        for i in range(3):
            zone = Location.objects.get_or_create(
                code=f"{warehouse.code}-Z{i+1:02d}",
                defaults={
                    "name": f"Zone {i+1}",
                    "parent": warehouse,
                    "type": location_types["zone"],
                }
            )[0]
            zones.append(zone)

    # Create racks in each zone
    racks = []
    for zone in zones:
        for i in range(5):
            rack = Location.objects.get_or_create(
                code=f"{zone.code}-R{i+1:02d}",
                defaults={
                    "name": f"Rack {i+1}",
                    "parent": zone,
                    "type": location_types["rack"],
                }
            )[0]
            racks.append(rack)

    # Create shelves in each rack
    shelves = []
    for rack in racks:
        for i in range(3):
            shelf = Location.objects.get_or_create(
                code=f"{rack.code}-SH{i+1:02d}",
                defaults={
                    "name": f"Shelf {i+1}",
                    "parent": rack,
                    "type": location_types["shelf"],
                }
            )[0]
            shelves.append(shelf)

    # Create bins in half the shelves
    bins = []
    for shelf in shelves[: len(shelves) // 2]:
        for i in range(3):
            bin_loc = Location.objects.get_or_create(
                code=f"{shelf.code}-BX{i+1:02d}",
                defaults={
                    "name": f"Bin {i+1}",
                    "parent": shelf,
                    "type": location_types["bin"],
                }
            )[0]
            bins.append(bin_loc)

    all_locations = racks + shelves + bins  # Products assigned to these levels

    # Generate product types
    product_types = [
        ("Widget A", "WGT-001", 5, "Standard widget type A"),
        ("Widget B", "WGT-002", 10, "Standard widget type B"),
        ("Gadget X", "GDG-001", 3, "Electronics - type X"),
        ("Gadget Y", "GDG-002", 7, "Electronics - type Y"),
        ("Connector Pro", "CNC-001", 15, "Industrial connectors"),
        ("Screw Pack M6", "SCR-M6", 100, "M6 screws, 50pcs"),
        ("Screw Pack M8", "SCR-M8", 100, "M8 screws, 50pcs"),
        ("Washer Set", "WSH-001", 50, "Assorted washers"),
        ("Bolt Kit", "BLT-KIT", 20, "Bolt assortment kit"),
        ("Cable Ties", "CBL-TIE", 500, "Cable ties pack"),
    ]

    print(f"Created {len(buildings)} buildings")
    print(f"Created {len(warehouses)} warehouses")
    print(f"Created {len(zones)} zones")
    print(f"Created {len(racks)} racks")
    print(f"Created {len(shelves)} shelves")
    print(f"Created {len(bins)} bins")

    # Generate products
    products = []
    for i in range(count_products):
        name, part_number, min_stock, description = random.choice(product_types)
        # Add suffix to make names unique but similar
        unique_name = f"{name} - {i+1:03d}"
        unique_part = f"{part_number}-{i+1:03d}"

        product, _ = Product.objects.get_or_create(
            name=unique_name,
            defaults={
                "part_number": unique_part,
                "description": description,
                "min_stock_level": min_stock,
            }
        )

        # Assign location to 80% of products
        if random.random() < 0.8:
            product.location = random.choice(all_locations)
            product.save()

        products.append(product)

    print(f"Created {len(products)} products (80% with locations)")

    # Generate tags
    tags = []
    for i in range(count_tags):
        # Generate realistic RFID tag format
        tag_id = f"E200{random.randint(10, 99):02d}{random.randint(100, 999):03d}{random.randint(0, 0xFFFFFFFF):08X}"
        tag, _ = Tag.objects.get_or_create(tag_id=tag_id)
        tags.append(tag)

    print(f"Created {len(tags)} tags")

    # Associate tags with products (1-3 tags per product)
    for product in products:
        num_tags = random.randint(1, 3)
        assigned_tags = random.sample(tags, min(num_tags, len(tags)))
        product.tags.set(assigned_tags)

    print(f"Associated tags with products")

    # Print summary
    total_locations = len(buildings) + len(warehouses) + len(zones) + len(racks) + len(shelves) + len(bins)
    print(f"\n=== Summary ===")
    print(f"Total locations: {total_locations}")
    print(f"Products: {Product.objects.count()}")
    print(f"Tags: {Tag.objects.count()}")
    print(f"Products with location: {Product.objects.exclude(location__isnull=True).count()}")
    print(f"Products without location: {Product.objects.filter(location__isnull=True).count()}")


if __name__ == "__main__":
    generate_test_data()