"""Refresh %-based hull prices from Jita on demand.

Runs inline (synchronous) by default so you see results immediately; pass
--async to enqueue the Celery per-type tasks instead (needs a worker).
"""

from django.core.management.base import BaseCommand

from shop.tasks import _apply_prices_for_type, _enqueue_pct_refreshes, pct_type_ids


class Command(BaseCommand):
    help = "Refresh %-priced hull listings from live Jita prices (Jita 4-4)."

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

    def handle(self, *args, **options):
        if options["use_async"]:
            type_ids = _enqueue_pct_refreshes()
            self.stdout.write(
                self.style.SUCCESS(f"Enqueued {len(type_ids)} per-type refresh task(s).")
            )
            return

        type_ids = pct_type_ids()
        if not type_ids:
            self.stdout.write("No %-priced hull listings to refresh.")
            return

        total = 0
        for type_id in type_ids:
            changed = _apply_prices_for_type(type_id)
            total += changed
            self.stdout.write(f"  type {type_id}: {changed} listing(s) updated")
        self.stdout.write(
            self.style.SUCCESS(
                f"Done — {total} listing(s) updated across {len(type_ids)} type(s)."
            )
        )
