import random
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.utils.text import slugify
from django.utils import timezone
from catalog_app.models import (
    Catalog, Category, Author, RightsType,
    Book, BookRight, CartItem, Order, OrderItem, Payment
)

User = get_user_model()

def run():
    # --- USERS ---
    admin, _ = User.objects.get_or_create(username="admin2", defaults={"email": "admin@example.com"})
    admin.set_password("admin123")
    admin.is_staff = True
    admin.is_superuser = True
    admin.save()

    user1, _ = User.objects.get_or_create(username="jane_doe", defaults={"email": "jane@example.com"})
    user1.set_password("password123")
    user1.save()

    user2, _ = User.objects.get_or_create(username="john_smith", defaults={"email": "john@example.com"})
    user2.set_password("password123")
    user2.save()

    print("✅ Users created")

    # --- CATALOGS ---
    catalogs = [
        ("African Literature", "Collection of modern and classic African works"),
        ("Global Fiction", "International stories and contemporary fiction"),
    ]
    catalog_objs = []
    for name, desc in catalogs:
        obj, _ = Catalog.objects.get_or_create(name=name, slug=slugify(name), defaults={"description": desc})
        catalog_objs.append(obj)
    print("✅ Catalogs created")

    # --- CATEGORIES ---
    categories = ["Fiction", "Non-Fiction", "Drama", "Poetry"]
    category_objs = []
    for name in categories:
        obj, _ = Category.objects.get_or_create(name=name, slug=slugify(name))
        category_objs.append(obj)
    print("✅ Categories created")

    # --- AUTHORS ---
    authors = [
        ("Chinua Achebe", "Author of 'Things Fall Apart'"),
        ("Ngũgĩ wa Thiong'o", "Kenyan novelist and academic"),
        ("Chimamanda Ngozi Adichie", "Author of 'Half of a Yellow Sun'"),
        ("C.S. Lewis", "British author of 'The Chronicles of Narnia'"),
    ]
    author_objs = []
    for name, bio in authors:
        obj, _ = Author.objects.get_or_create(name=name, defaults={"bio": bio})
        author_objs.append(obj)
    print("✅ Authors created")

    # --- RIGHTS TYPES ---
    rights = [
        ("TRANSLATION", "Translation Rights", "Right to translate the book into another language"),
        ("FILM", "Film Rights", "Right to adapt the book into a movie"),
        ("AUDIO", "Audio Rights", "Right to produce an audiobook version"),
        ("DIGITAL", "Digital Rights", "Right to distribute the book digitally"),
    ]
    rights_objs = []
    for code, name, desc in rights:
        obj, _ = RightsType.objects.get_or_create(code=code, defaults={"name": name, "description": desc})
        rights_objs.append(obj)
    print("✅ Rights Types created")

    # --- BOOKS ---
    books_data = [
        ("Things Fall Apart", "Classic African novel", 1958, "9780385474542", 0),
        ("Petals of Blood", "Post-colonial narrative", 1977, "9780435908442", 0),
        ("Half of a Yellow Sun", "Nigerian civil war novel", 2006, "9780007200283", 1),
        ("The Lion, the Witch and the Wardrobe", "Children’s fantasy classic", 1950, "9780064471046", 1),
        ("The Screwtape Letters", "Satirical Christian fiction", 1942, "9780060652937", 1),
        ("Weep Not, Child", "Kenyan independence story", 1964, "9780435908305", 0),
    ]

    book_objs = []
    for title, desc, year, isbn, catalog_idx in books_data:
        obj, _ = Book.objects.get_or_create(
            title=title,
            catalog=catalog_objs[catalog_idx],
            category=random.choice(category_objs),
            author=random.choice(author_objs),
            defaults={
                "description": desc,
                "publication_year": year,
                "isbn": isbn,
            },
        )
        book_objs.append(obj)
    print("✅ Books created")

    # --- BOOK RIGHTS ---
    for book in book_objs:
        for right in random.sample(rights_objs, k=random.randint(2, len(rights_objs))):
            BookRight.objects.get_or_create(
                book=book,
                rights_type=right,
                defaults={
                    "price": Decimal(random.randint(100, 1000)),
                    "currency": "USD",
                    "exclusive": random.choice([True, False]),
                    "available_quantity": random.randint(1, 10),
                    "status": "AVAILABLE",
                },
            )
    print("✅ Book Rights created")

    # --- SAMPLE CART ITEM ---
    sample_right = BookRight.objects.first()
    if sample_right:
        CartItem.objects.get_or_create(user=user1, book_right=sample_right, quantity=2)
    print("✅ Cart item created")

    # --- SAMPLE ORDER ---
    if sample_right:
        order = Order.objects.create(
            user=user1,
            total_amount=sample_right.price * 2,
            currency="USD",
            status="PAID",
        )
        OrderItem.objects.create(
            order=order,
            book_right=sample_right,
            unit_price=sample_right.price,
            quantity=2,
            total_price=sample_right.price * 2,
            rights_snapshot={
                "book": sample_right.book.title,
                "right_type": sample_right.rights_type.code,
                "price": str(sample_right.price),
            },
        )
        Payment.objects.create(
            order=order,
            provider="Stripe",
            provider_payment_id="PAY123456",
            amount=order.total_amount,
            currency="USD",
            status="SUCCESS",
        )
    print("✅ Sample Order and Payment created")

    print("🎉 Database seeding complete!")
