# -*- coding: utf-8 -*-
# your_app/management/commands/count_active.py

from django.core.management.base import BaseCommand
from django.apps import apps
from django.db.models import Q


class Command(BaseCommand):
    help = (
        "Liczy rekordy łącznie, aktywne, nieaktywne, nieznane (NULL) oraz ile ma check_active=True.\n"
        "Przykład:\n"
        "  python manage.py count_active --model extractly.AdsManual\n"
        "Opcjonalne pola:\n"
        "  --active-field is_active (domyślnie)\n"
        "  --check-field  check_active (domyślnie)\n"
        "Tryb cichy (CSV):\n"
        "  python manage.py count_active --model extractly.AdsManual --quiet\n"
        "  Kolumny: total,active,inactive,unknown,check_true\n"
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--model",
            required=True,
            help="Model w formacie app_label.ModelName, np. extractly.AdsManual",
        )
        parser.add_argument(
            "--active-field",
            default="is_active",
            help="Nazwa pola boolean określającego aktywność (domyślnie: is_active).",
        )
        parser.add_argument(
            "--check-field",
            default="check_active",
            help="Nazwa pola boolean do zliczenia (domyślnie: check_active).",
        )
        parser.add_argument(
            "--quiet",
            action="store_true",
            help="Wypisuje tylko liczby (CSV: total,active,inactive,unknown,check_true).",
        )

    def handle(self, *args, **opts):
        model_label = opts["model"]
        active_field = opts["active_field"]
        check_field = opts["check_field"]
        quiet = opts["quiet"]

        try:
            Model = apps.get_model(model_label)
        except LookupError:
            raise SystemExit(self.style.ERROR(f"Model '{model_label}' nie istnieje."))

        field_names = {f.name for f in Model._meta.get_fields()}

        if active_field not in field_names:
            raise SystemExit(
                self.style.ERROR(f"Pole '{active_field}' nie istnieje w modelu {model_label}.")
            )

        # Podstawowe zliczenia
        total = Model.objects.all().count()
        active = Model.objects.filter(**{active_field: True}).count()
        inactive = Model.objects.filter(**{active_field: False}).count()
        unknown = Model.objects.filter(Q(**{f"{active_field}__isnull": True})).count()

        # Zliczenie check_field=True (jeśli istnieje)
        if check_field in field_names:
            check_true = Model.objects.filter(**{check_field: True}).count()
            check_field_present = True
        else:
            check_true = 0
            check_field_present = False

        if quiet:
            # CSV: total,active,inactive,unknown,check_true
            self.stdout.write(f"{total},{active},{inactive},{unknown},{check_true}")
            return

        # Ładny, opisowy output
        self.stdout.write(self.style.SUCCESS("== Podsumowanie =="))
        self.stdout.write(f"Model:           {model_label}")
        self.stdout.write(f"Pole aktywności: {active_field}")
        if check_field_present:
            self.stdout.write(f"Pole check:      {check_field}\n")
        else:
            self.stdout.write(self.style.WARNING(
                f"Pole check '{check_field}' nie istnieje w modelu — pomijam zliczanie.\n"
            ))

        self.stdout.write(f"Łącznie:         {total}")
        self.stdout.write(self.style.SUCCESS(f"Aktywne:         {active}"))
        self.stdout.write(self.style.WARNING(f"Nieaktywne:      {inactive}"))
        self.stdout.write(self.style.NOTICE(f"Nieznane (NULL): {unknown}"))
        if check_field_present:
            self.stdout.write(self.style.SUCCESS(f"{check_field}=True:  {check_true}"))

        # Dodatkowa kontrola spójności
        if (active + inactive + unknown) != total:
            other = total - (active + inactive + unknown)
            self.stdout.write(self.style.ERROR(f"\nUWAGA: {other} rekord(ów) poza standardowym podziałem."))
