"""Recompute stored hull stock for shops with auto-stock listings.

Runs inline (synchronous) by default; pass --async to enqueue the Celery
per-shop tasks instead (needs a worker).
"""

from django.core.management.base import BaseCommand

from shop.models import AUTO_STOCK, Shop
from shop.stock import recompute_shop_stock
from shop.tasks import _enqueue_stock_refreshes


class Command(BaseCommand):
    help = "Recompute stored hull stock for shops with auto-stock listings."

    def add_arguments(self, parser):
        parser.add_argument(
            "--async",
            action="store_true",
            dest="use_async",
            help="Enqueue Celery per-shop tasks instead of running inline.",
        )

    def handle(self, *args, **options):
        if options["use_async"]:
            shop_ids = _enqueue_stock_refreshes()
            self.stdout.write(
                self.style.SUCCESS(f"Enqueued {len(shop_ids)} shop refresh task(s).")
            )
            return

        shops = list(
            Shop.objects.filter(hull_listings__stock_mode=AUTO_STOCK).distinct()
        )
        if not shops:
            self.stdout.write("No shops with auto-stock listings.")
            return
        for shop in shops:
            recompute_shop_stock(shop)
            self.stdout.write(f"  {shop.slug}: recomputed")
        self.stdout.write(self.style.SUCCESS(f"Done — {len(shops)} shop(s)."))
