"""Management command: seed_data

Populates the database with sample bookstore data so you can immediately
try out django-shreck's TUI features. Safe to run multiple times (idempotent).

Usage:
    python manage.py seed_data
"""
from __future__ import annotations

import datetime

from django.core.management.base import BaseCommand

from bookstore.models import Author, Book, Genre, Order


class Command(BaseCommand):
    help = "Seed the database with sample bookstore data."

    def handle(self, *args, **options) -> None:  # noqa: ANN002, ANN003
        self.stdout.write("🌱  Seeding bookstore data…")

        # ── Genres ────────────────────────────────────────────────────────────
        fiction, _ = Genre.objects.get_or_create(
            name="Fiction",
            defaults={"description": "Novels and short stories of an imaginative nature."},
        )
        dystopia, _ = Genre.objects.get_or_create(
            name="Dystopian",
            defaults={"description": "Stories set in a totalitarian or post-apocalyptic future."},
        )
        scifi, _ = Genre.objects.get_or_create(
            name="Science Fiction",
            defaults={"description": "Speculative fiction grounded in science and technology."},
        )
        mystery, _ = Genre.objects.get_or_create(
            name="Mystery",
            defaults={"description": "Whodunit and detective fiction."},
        )

        # ── Authors ───────────────────────────────────────────────────────────
        orwell, _ = Author.objects.get_or_create(
            first_name="George",
            last_name="Orwell",
            defaults={
                "born": datetime.date(1903, 6, 25),
                "bio": "English novelist and essayist, journalist and critic.",
            },
        )
        huxley, _ = Author.objects.get_or_create(
            first_name="Aldous",
            last_name="Huxley",
            defaults={
                "born": datetime.date(1894, 7, 26),
                "bio": "English writer and philosopher known for Brave New World.",
            },
        )
        asimov, _ = Author.objects.get_or_create(
            first_name="Isaac",
            last_name="Asimov",
            defaults={
                "born": datetime.date(1920, 1, 2),
                "bio": "American author of science fiction and popular science.",
            },
        )
        christie, _ = Author.objects.get_or_create(
            first_name="Agatha",
            last_name="Christie",
            defaults={
                "born": datetime.date(1890, 9, 15),
                "bio": "English writer known for her detective novels.",
            },
        )

        # ── Books ─────────────────────────────────────────────────────────────
        books_data = [
            {
                "title": "Nineteen Eighty-Four",
                "author": orwell,
                "genre": dystopia,
                "published": datetime.date(1949, 6, 8),
                "isbn": "978-0-451-52493-5",
                "price": "9.99",
            },
            {
                "title": "Animal Farm",
                "author": orwell,
                "genre": fiction,
                "published": datetime.date(1945, 8, 17),
                "isbn": "978-0-452-28424-1",
                "price": "7.99",
            },
            {
                "title": "Brave New World",
                "author": huxley,
                "genre": dystopia,
                "published": datetime.date(1932, 8, 1),
                "isbn": "978-0-060-85052-4",
                "price": "10.99",
            },
            {
                "title": "Point Counter Point",
                "author": huxley,
                "genre": fiction,
                "published": datetime.date(1928, 10, 1),
                "isbn": "978-1-564-78230-9",
                "price": "12.50",
                "in_stock": False,
            },
            {
                "title": "Foundation",
                "author": asimov,
                "genre": scifi,
                "published": datetime.date(1951, 5, 1),
                "isbn": "978-0-553-29335-7",
                "price": "11.99",
            },
            {
                "title": "I, Robot",
                "author": asimov,
                "genre": scifi,
                "published": datetime.date(1950, 12, 2),
                "isbn": "978-0-553-29438-5",
                "price": "8.99",
            },
            {
                "title": "Murder on the Orient Express",
                "author": christie,
                "genre": mystery,
                "published": datetime.date(1934, 1, 1),
                "isbn": "978-0-062-69366-0",
                "price": "8.49",
            },
            {
                "title": "And Then There Were None",
                "author": christie,
                "genre": mystery,
                "published": datetime.date(1939, 11, 6),
                "isbn": "978-0-062-69367-7",
                "price": "8.49",
            },
        ]

        books = []
        for data in books_data:
            in_stock = data.pop("in_stock", True)
            book, created = Book.objects.get_or_create(
                isbn=data["isbn"],
                defaults={**data, "in_stock": in_stock},
            )
            books.append(book)
            if created:
                self.stdout.write(f"  📚  Created: {book}")

        # ── Orders ────────────────────────────────────────────────────────────
        orders_data = [
            {"book": books[0], "quantity": 2, "customer_email": "alice@example.com", "shipped": True},
            {"book": books[1], "quantity": 1, "customer_email": "bob@example.com", "shipped": True},
            {"book": books[2], "quantity": 3, "customer_email": "carol@example.com"},
            {"book": books[4], "quantity": 1, "customer_email": "dave@example.com"},
            {"book": books[5], "quantity": 2, "customer_email": "alice@example.com"},
            {"book": books[6], "quantity": 1, "customer_email": "eve@example.com", "shipped": True},
            {"book": books[7], "quantity": 4, "customer_email": "frank@example.com"},
            {"book": books[0], "quantity": 1, "customer_email": "grace@example.com"},
            {"book": books[3], "quantity": 1, "customer_email": "heidi@example.com"},
            {"book": books[2], "quantity": 2, "customer_email": "ivan@example.com"},
        ]

        existing_orders = Order.objects.count()
        if existing_orders == 0:
            for data in orders_data:
                Order.objects.create(**data)
            self.stdout.write(f"  🛒  Created {len(orders_data)} orders.")
        else:
            self.stdout.write(f"  🛒  Orders already exist ({existing_orders}), skipping.")

        self.stdout.write(self.style.SUCCESS("✅  Done! Run: python manage.py shreck"))

