# manual_agregator/management/commands/sync_inactive.py
from django.core.management.base import BaseCommand, CommandError
from houslyspace.tasks import task_send_inactive_ads_to_cloud

class Command(BaseCommand):
    help = (
        "Wyślij nieaktywne ogłoszenia do chmury (endpoint receive-inactive).\n"
        "Domyślnie uruchamia task Celery (async). Możesz użyć --eager, aby wykonać od razu (sync)."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--mode",
            choices=["batch", "pipeline"],
            default="batch",
            help="batch = jedna paczka i koniec; pipeline = uruchamia się w pętli z lockiem."
        )
        parser.add_argument(
            "--limit",
            type=int,
            default=None,
            help="Rozmiar paczki (domyślnie wartość z settings: ADS_INACTIVE_BATCH_SIZE)."
        )
        parser.add_argument(
            "--timeout",
            type=int,
            default=None,
            help="Timeout requestu (domyślnie wartość z settings: ADS_INACTIVE_TIMEOUT)."
        )
        parser.add_argument(
            "--eager",
            action="store_true",
            help="Uruchom synchronicznie w tym samym procesie (bez Celery)."
        )
        parser.add_argument(
            "--wait",
            action="store_true",
            help="(Tylko async) Poczekaj na wynik taska i wypisz rezultat."
        )
        parser.add_argument(
            "--queue-timeout",
            type=int,
            default=600,
            help="Ile maksymalnie czekać (sek) na wynik przy --wait (domyślnie 600)."
        )

    def handle(self, *args, **options):
        mode = options["mode"]
        limit = options["limit"]
        timeout = options["timeout"]
        eager = options["eager"]
        wait = options["wait"]
        queue_timeout = options["queue_timeout"]

        kwargs = {"mode": mode}
        if limit is not None:
            kwargs["limit"] = int(limit)
        if timeout is not None:
            kwargs["timeout"] = int(timeout)

        if eager:
            # Run synchronously in-process (no Celery worker needed).
            self.stdout.write(self.style.WARNING(
                f"[sync_inactive] Running EAGER (sync) with kwargs={kwargs}"
            ))
            res = task_send_inactive_ads_to_cloud.apply(kwargs=kwargs)  # execute now
            try:
                result = res.get(propagate=True)
            except Exception as e:
                raise CommandError(f"EAGER run failed: {e}") from e
            self.stdout.write(self.style.SUCCESS(f"[sync_inactive] Done (eager): {result}"))
            return

        # Async via Celery
        self.stdout.write(f"[sync_inactive] Enqueuing Celery task with kwargs={kwargs}")
        async_res = task_send_inactive_ads_to_cloud.apply_async(kwargs=kwargs)
        self.stdout.write(self.style.SUCCESS(f"[sync_inactive] Task enqueued: id={async_res.id}"))

        if wait:
            self.stdout.write(f"[sync_inactive] Waiting for result (up to {queue_timeout}s)…")
            try:
                result = async_res.get(timeout=queue_timeout, propagate=True)
            except Exception as e:
                raise CommandError(f"Waiting failed: {e}") from e
            self.stdout.write(self.style.SUCCESS(f"[sync_inactive] Result: {result}"))
