from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone

from extractly.models import NetworkMonitoredPage, AdsManual


class Command(BaseCommand):
    help = (
        "Synchronizuje is_active/inactive_date pomiędzy NetworkMonitoredPage i AdsManual.\n"
        "Domyślnie: NetworkMonitoredPage → AdsManual.\n"
        "Opcja --reverse przełącza na AdsManual → NetworkMonitoredPage.\n"
        "Użyj --dry-run żeby zobaczyć plan zmian bez zapisu.\n"
        "Opcjonalnie ogranicz po źródle: --source-id=<UUID SourceNetwork>."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--source-id",
            type=str,
            default=None,
            help="UUID SourceNetwork, aby ograniczyć synchronizację do jednego źródła.",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Pokaż liczbę zmian, ale nic nie zapisuj.",
        )
        parser.add_argument(
            "--reverse",
            action="store_true",
            help="Synchronizuj w odwrotną stronę: AdsManual → NetworkMonitoredPage.",
        )

    def handle(self, *args, **options):
        source_id = options.get("source_id")
        dry_run = options.get("dry_run", False)
        reverse = options.get("reverse", False)
        now = timezone.now()

        if reverse:
            # AdsManual -> NetworkMonitoredPage
            base_page_filter = {}
            if source_id:
                base_page_filter["source_id"] = source_id

            qs_deactivate_pages = NetworkMonitoredPage.objects.filter(
                **base_page_filter,
                is_active=True,
                network_ad_manual__isnull=False,
                network_ad_manual__is_active=False,
            )
            qs_activate_pages = NetworkMonitoredPage.objects.filter(
                **base_page_filter,
                is_active=False,
                network_ad_manual__isnull=False,
                network_ad_manual__is_active=True,
            )

            to_deactivate = qs_deactivate_pages.count()
            to_activate = qs_activate_pages.count()

            if dry_run:
                self.stdout.write(
                    f"[DRY-RUN] NetworkMonitoredPage: do dezaktywacji {to_deactivate}, do aktywacji {to_activate}"
                )
                return

            with transaction.atomic():
                if to_deactivate:
                    qs_deactivate_pages.update(is_active=False, inactive_date=now)
                if to_activate:
                    qs_activate_pages.update(is_active=True, inactive_date=None)

            self.stdout.write(
                self.style.SUCCESS(
                    f"Zaktualizowano NetworkMonitoredPage — dezaktywowane: {to_deactivate}, aktywowane: {to_activate}"
                )
            )

        else:
            # Domyślnie: NetworkMonitoredPage -> AdsManual
            base_manual_filter = {}
            if source_id:
                base_manual_filter["networkmonitoredpage__source_id"] = source_id

            # Dezaktywuj AdsManual, gdy powiązana strona jest nieaktywna
            qs_deactivate_manual = AdsManual.objects.filter(
                **base_manual_filter,
                is_active=True,
                networkmonitoredpage__isnull=False,
                networkmonitoredpage__is_active=False,
            )

            # Aktywuj AdsManual, gdy powiązana strona jest aktywna
            qs_activate_manual = AdsManual.objects.filter(
                **base_manual_filter,
                is_active=False,
                networkmonitoredpage__isnull=False,
                networkmonitoredpage__is_active=True,
            )

            to_deactivate = qs_deactivate_manual.count()
            to_activate = qs_activate_manual.count()

            if dry_run:
                self.stdout.write(
                    f"[DRY-RUN] AdsManual: do dezaktywacji {to_deactivate}, do aktywacji {to_activate}"
                )
                return

            with transaction.atomic():
                if to_deactivate:
                    qs_deactivate_manual.update(is_active=False, inactive_date=now)
                if to_activate:
                    qs_activate_manual.update(is_active=True, inactive_date=None)

            self.stdout.write(
                self.style.SUCCESS(
                    f"Zaktualizowano AdsManual — dezaktywowane: {to_deactivate}, aktywowane: {to_activate}"
                )
            )
