"""Recompute stored stock (all sections) for shops that source from stockrooms.

Runs inline (synchronous) by default; pass --async to enqueue the Celery
per-shop tasks instead (needs a worker). Does not pull upstream ESI/corptools
data — that's the periodic `refresh_all_stock` task's job.
"""

from django.core.management.base import BaseCommand

from shop.models import Shop
from shop.sections.base import handlers
from shop.tasks import _enqueue_stock_refreshes, _refresh_shop_stock


class Command(BaseCommand):
    help = "Recompute stored stock (all sections) for shops sourcing from stockrooms."

    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

        shop_ids = set()
        for handler in handlers():
            shop_ids.update(handler.shops_to_recompute())
        if not shop_ids:
            self.stdout.write("No shops with recomputable stock.")
            return
        slugs = dict(Shop.objects.filter(pk__in=shop_ids).values_list("pk", "slug"))
        for shop_id in sorted(shop_ids):
            _refresh_shop_stock(shop_id)
            self.stdout.write(f"  {slugs.get(shop_id, shop_id)}: recomputed")
        self.stdout.write(self.style.SUCCESS(f"Done — {len(shop_ids)} shop(s)."))
