"""
E-commerce Application Example

Demonstrates an e-commerce system with products, customers, orders, and inventory.
"""

from datetime import datetime, timedelta
import random
from vibedb import VibeDB, Q


def main():
    print("🛒 VibeDB E-commerce Application Example\n")

    # Create database
    db = VibeDB("ecommerce.db")

    # Get collections
    products = db.collection("products")
    customers = db.collection("customers")
    orders = db.collection("orders")
    inventory = db.collection("inventory")

    # Clear existing data for demo
    products.delete_many({})
    customers.delete_many({})
    orders.delete_many({})
    inventory.delete_many({})

    print("1️⃣  Setting up schemas...\n")

    # Define schemas
    products.set_schema({
        "name": {"type": "string", "required": True},
        "description": {"type": "string"},
        "price": {"type": "number", "required": True, "min": 0},
        "category": {"type": "string", "required": True},
        "tags": {"type": "array", "items": {"type": "string"}},
        "rating": {"type": "number", "min": 0, "max": 5},
        "reviews_count": {"type": "integer", "min": 0, "default": 0},
        "active": {"type": "boolean", "default": True},
    })

    customers.set_schema({
        "name": {"type": "string", "required": True},
        "email": {"type": "string", "required": True, "unique": True},
        "phone": {"type": "string"},
        "address": {"type": "object"},
        "tier": {"type": "string", "enum": ["bronze", "silver", "gold"], "default": "bronze"},
        "total_spent": {"type": "number", "min": 0, "default": 0},
    })

    orders.set_schema({
        "customer_id": {"type": "string", "required": True},
        "items": {"type": "array", "required": True},
        "total": {"type": "number", "required": True, "min": 0},
        "status": {"type": "string", "enum": ["pending", "paid", "shipped", "delivered", "cancelled"], "default": "pending"},
        "payment_method": {"type": "string"},
        "shipping_address": {"type": "object"},
    })

    inventory.set_schema({
        "product_id": {"type": "string", "required": True, "unique": True},
        "quantity": {"type": "integer", "required": True, "min": 0},
        "warehouse": {"type": "string", "required": True},
        "last_restock": {"type": "integer"},  # Unix timestamp
    })

    print("2️⃣  Creating products...\n")

    # Create products
    laptop_id = products.insert({
        "name": "UltraBook Pro 15",
        "description": "Powerful laptop for professionals",
        "price": 1299.99,
        "category": "electronics",
        "tags": ["laptop", "computer", "professional"],
        "rating": 4.5,
        "reviews_count": 128
    })

    mouse_id = products.insert({
        "name": "Wireless Mouse MX3",
        "description": "Ergonomic wireless mouse",
        "price": 49.99,
        "category": "electronics",
        "tags": ["mouse", "wireless", "accessories"],
        "rating": 4.7,
        "reviews_count": 342
    })

    desk_id = products.insert({
        "name": "Standing Desk Pro",
        "description": "Adjustable standing desk",
        "price": 399.99,
        "category": "furniture",
        "tags": ["desk", "standing", "office"],
        "rating": 4.3,
        "reviews_count": 89
    })

    chair_id = products.insert({
        "name": "Ergonomic Office Chair",
        "description": "Comfortable chair for long work sessions",
        "price": 299.99,
        "category": "furniture",
        "tags": ["chair", "ergonomic", "office"],
        "rating": 4.6,
        "reviews_count": 156
    })

    monitor_id = products.insert({
        "name": "4K Monitor 27\"",
        "description": "Ultra HD monitor with great colors",
        "price": 449.99,
        "category": "electronics",
        "tags": ["monitor", "display", "4k"],
        "rating": 4.8,
        "reviews_count": 203
    })

    print(f"  ✓ Created {products.count()} products")

    print("\n3️⃣  Setting up inventory...\n")

    # Create inventory records
    for product_id, qty, warehouse in [
        (laptop_id, 45, "Warehouse A"),
        (mouse_id, 200, "Warehouse B"),
        (desk_id, 30, "Warehouse A"),
        (chair_id, 55, "Warehouse A"),
        (monitor_id, 75, "Warehouse B"),
    ]:
        inventory.insert({
            "product_id": product_id,
            "quantity": qty,
            "warehouse": warehouse,
            "last_restock": int(datetime.now().timestamp())
        })

    print(f"  ✓ Created {inventory.count()} inventory records")

    print("\n4️⃣  Creating customers...\n")

    # Create customers
    customer_ids = []

    customer_ids.append(customers.insert({
        "name": "Alice Johnson",
        "email": "alice@example.com",
        "phone": "+1-555-0101",
        "address": {
            "street": "123 Main St",
            "city": "New York",
            "state": "NY",
            "zip": "10001"
        },
        "tier": "gold",
        "total_spent": 2500.00
    }))

    customer_ids.append(customers.insert({
        "name": "Bob Smith",
        "email": "bob@example.com",
        "phone": "+1-555-0102",
        "address": {
            "street": "456 Oak Ave",
            "city": "Los Angeles",
            "state": "CA",
            "zip": "90001"
        },
        "tier": "silver",
        "total_spent": 850.00
    }))

    customer_ids.append(customers.insert({
        "name": "Charlie Brown",
        "email": "charlie@example.com",
        "phone": "+1-555-0103",
        "address": {
            "street": "789 Pine Rd",
            "city": "Chicago",
            "state": "IL",
            "zip": "60601"
        },
        "tier": "bronze",
        "total_spent": 150.00
    }))

    print(f"  ✓ Created {customers.count()} customers")

    print("\n5️⃣  Creating orders...\n")

    # Alice's order - laptop and mouse
    order1_id = orders.insert({
        "customer_id": customer_ids[0],
        "items": [
            {"product_id": laptop_id, "quantity": 1, "price": 1299.99},
            {"product_id": mouse_id, "quantity": 1, "price": 49.99}
        ],
        "total": 1349.98,
        "status": "delivered",
        "payment_method": "credit_card",
        "shipping_address": customers.get(customer_ids[0])["address"]
    })

    # Bob's order - desk and chair
    order2_id = orders.insert({
        "customer_id": customer_ids[1],
        "items": [
            {"product_id": desk_id, "quantity": 1, "price": 399.99},
            {"product_id": chair_id, "quantity": 1, "price": 299.99}
        ],
        "total": 699.98,
        "status": "shipped",
        "payment_method": "paypal",
        "shipping_address": customers.get(customer_ids[1])["address"]
    })

    # Charlie's order - monitor
    order3_id = orders.insert({
        "customer_id": customer_ids[2],
        "items": [
            {"product_id": monitor_id, "quantity": 1, "price": 449.99}
        ],
        "total": 449.99,
        "status": "pending",
        "payment_method": "credit_card",
        "shipping_address": customers.get(customer_ids[2])["address"]
    })

    print(f"  ✓ Created {orders.count()} orders")

    print("\n6️⃣  Creating indexes...\n")

    # Create indexes for common queries
    products.create_index(["category"])
    products.create_index(["price"])
    products.create_index(["rating"])
    customers.create_index(["email"], unique=True)
    customers.create_index(["tier"])
    orders.create_index(["customer_id"])
    orders.create_index(["status"])
    inventory.create_index(["product_id"], unique=True)

    print("  ✓ Created indexes for fast queries")

    print("\n7️⃣  Running queries...\n")

    # Query: All electronics products
    electronics = products.find(Q.eq("category", "electronics")).to_list()
    print(f"  💻 Electronics products: {len(electronics)}")

    # Query: Products under $100
    affordable = products.find(Q.lt("price", 100)).sort("price", 1).to_list()
    print(f"  💰 Products under $100:")
    for product in affordable:
        print(f"     • {product.name}: ${product.price}")

    # Query: High-rated products (>4.5 stars)
    top_rated = products.find(Q.gt("rating", 4.5)).sort("rating", -1).to_list()
    print(f"\n  ⭐ High-rated products (>4.5 stars):")
    for product in top_rated:
        print(f"     • {product.name}: {product.rating} stars ({product.reviews_count} reviews)")

    # Query: Gold tier customers
    gold_customers = customers.find(Q.eq("tier", "gold")).to_list()
    print(f"\n  👑 Gold tier customers:")
    for customer in gold_customers:
        print(f"     • {customer.name}: ${customer.total_spent:.2f} spent")

    # Query: Active orders (not delivered or cancelled)
    active_orders = orders.find(
        Q.nin("status", ["delivered", "cancelled"])
    ).to_list()
    print(f"\n  📦 Active orders: {len(active_orders)}")
    for order in active_orders:
        customer = customers.get(order.customer_id)
        print(f"     • Order for {customer.name}: ${order.total:.2f} ({order.status})")

    # Query: Low stock items (quantity < 50)
    low_stock = inventory.find(Q.lt("quantity", 50)).to_list()
    print(f"\n  ⚠️  Low stock items:")
    for item in low_stock:
        product = products.get(item.product_id)
        print(f"     • {product.name}: {item.quantity} units in {item.warehouse}")

    # Complex query: Electronics under $500 with rating > 4.0
    good_deals = products.find(
        Q.eq("category", "electronics") &
        Q.lt("price", 500) &
        Q.gt("rating", 4.0)
    ).sort("price", 1).to_list()
    print(f"\n  🎯 Good electronics deals (<$500, >4.0 stars):")
    for product in good_deals:
        print(f"     • {product.name}: ${product.price} ({product.rating} stars)")

    print("\n8️⃣  Business analytics...\n")

    # Total revenue from delivered orders
    delivered_orders = orders.find(Q.eq("status", "delivered")).to_list()
    total_revenue = sum(order.total for order in delivered_orders)
    print(f"  💵 Total revenue (delivered): ${total_revenue:.2f}")

    # Average order value
    all_orders = orders.find({}).to_list()
    avg_order_value = sum(order.total for order in all_orders) / len(all_orders)
    print(f"  📊 Average order value: ${avg_order_value:.2f}")

    # Most popular category
    categories = {}
    for product in products.find({}):
        categories[product.category] = categories.get(product.category, 0) + 1
    most_popular = max(categories.items(), key=lambda x: x[1])
    print(f"  🏆 Most popular category: {most_popular[0]} ({most_popular[1]} products)")

    # Customer distribution by tier
    tiers = {}
    for customer in customers.find({}):
        tiers[customer.tier] = tiers.get(customer.tier, 0) + 1
    print(f"  👥 Customers by tier:")
    for tier, count in sorted(tiers.items()):
        print(f"     • {tier.capitalize()}: {count}")

    print("\n9️⃣  Database statistics...\n")

    stats = db.stats()
    print(f"  📊 Collections: {stats['collection_count']}")
    print(f"  📄 Total documents: {stats['total_documents']}")
    print(f"  💾 Database size: {stats.get('size_mb', 0):.2f} MB")

    print(f"\n  Products: {products.count()}")
    print(f"  Customers: {customers.count()}")
    print(f"  Orders: {orders.count()}")
    print(f"  Inventory: {inventory.count()}")

    print("\n🔟 Testing updates and upserts...\n")

    # Update product price
    laptop = products.get(laptop_id)
    new_price = laptop.price * 0.9  # 10% discount
    products.update(laptop_id, {"price": new_price})
    print(f"  ✓ Applied 10% discount to {laptop.name}: ${laptop.price:.2f} → ${new_price:.2f}")

    # Update order status
    orders.update(order3_id, {"status": "paid"})
    print(f"  ✓ Updated order status to 'paid'")

    # Upsert inventory (update if exists, insert if not)
    new_product_id = products.insert({
        "name": "Keyboard Mechanical",
        "price": 89.99,
        "category": "electronics",
        "tags": ["keyboard", "mechanical"],
        "rating": 4.4,
        "reviews_count": 67
    })

    inventory_id = inventory.upsert(
        {"product_id": new_product_id},
        {"product_id": new_product_id, "quantity": 150, "warehouse": "Warehouse B"}
    )
    print(f"  ✓ Upserted inventory for new product")

    print("\n✅ E-commerce application demo complete!")
    print(f"\n💡 Try launching Studio UI to explore the data: db.studio()")

    db.close()


if __name__ == "__main__":
    main()
