import logging

from django.core.management.base import BaseCommand
from django.db.models import Count

from apps.herd.models import Rancher

logger = logging.getLogger("merge_duplicate_ranchers")
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")  # noqa
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)


class Command(BaseCommand):
    help = "Merge ranchers with duplicate national_code and reassign their herds to one main rancher"

    def handle(self, *args, **options):
        duplicates = (
            Rancher.objects.values("national_code")
            .annotate(count=Count("id"))
            .filter(count__gt=1)
        )

        for duplicate in duplicates:
            ranchers = Rancher.objects.filter(national_code=duplicate["national_code"])
            main_rancher = ranchers.first()
            for rancher in ranchers:
                if rancher != main_rancher:
                    logger.info(f"Merging rancher {rancher.id} into {main_rancher.id}")
                    rancher.herd.update(rancher=main_rancher)
                    rancher.soft_delete()
                    logger.info(f"Rancher {rancher.id} merged into {main_rancher.id}")
                    logger.info(f"Rancher {rancher.id} deleted")

        self.stdout.write(self.style.SUCCESS("🎯 Merge process completed successfully."))
