import pandas as pd
from django.core.management.base import BaseCommand
from apps.herd.models import Rancher
from apps.herd.models import Herd
from apps.authentication.models import Province, City, Organization


class Command(BaseCommand):
    help = "Import Rancher and Herd data from Excel"

    def add_arguments(self, parser):
        parser.add_argument('excel_path', type=str)

    def handle(self, *args, **options):
        path = options['excel_path']
        df = pd.read_excel(path)
        records = df.to_dict(orient='records')

        self.stdout.write(self.style.SUCCESS(f"{len(records)} records loaded."))

        ranchers_to_create = []
        herds_to_create = []

        province_cache = {p.id: p for p in Province.objects.all()}
        city_cache = {c.id: c for c in City.objects.all()}
        org_cache = {o.id: o for o in Organization.objects.all()}

        for r in records:
            full_name = str(r.get("fullname") or "").strip()
            first_name = full_name.split(" ")[0] if full_name else ""
            last_name = " ".join(full_name.split(" ")[1:]) if len(full_name.split(" ")) > 1 else ""

            # province = province_cache.get((Province.objects.get(name=r.get("province"))).id)
            province = Province.objects.get(id=1)
            city = City.objects.get(id=1)

            rancher = Rancher(
                first_name=first_name,
                last_name=last_name,
                mobile=r.get("mobile"),
                national_code=r.get("national_id"),
                address="",
                province=province,
                city=city,
                without_herd=not bool(r.get("herd_code"))
            )
            ranchers_to_create.append(rancher)

        # ذخیره‌ی دامداران
        Rancher.objects.bulk_create(ranchers_to_create, batch_size=10000)
        self.stdout.write(self.style.SUCCESS(f"✅ Created {len(ranchers_to_create)} ranchers."))

        # بازیابی مجدد همه‌ی دامداران برای نگاشت herd
        rancher_cache = {r.national_code: r for r in Rancher.objects.all()}

        for r in records:
            if not r.get("herd_code"):
                print("not herd code")
                continue

            province = Province.objects.get(id=1)
            city = City.objects.get(id=1)
            coop = Organization.objects.get(id=1)
            print(f"province {province}")
            print(f"city {city}")
            print(f"coop {coop}")

            key = r.get("national_id")
            print(f'key {key}')
            rancher = Rancher.objects.get(national_code=key)
            print(f'ranchers {rancher}')
            if not rancher:
                print("not rancher")
                continue

            herd = Herd(
                code=r.get("herd_code"),
                name=r.get("herd_name"),
                rancher=rancher,
                province=province,
                city=city,
                postal=r.get("postal_code"),
                institution=r.get("unit_id"),
                epidemiologic=r.get("epidemiological_code"),
                cooperative=coop,
                heavy_livestock_number=r.get("heavy_livestock") or 0,
                light_livestock_number=r.get("light_livestock") or 0,
            )
            print(herd)
            herds_to_create.append(herd)
            print(herds_to_create)

        Herd.objects.bulk_create(herds_to_create, batch_size=10000)
        self.stdout.write(self.style.SUCCESS(f"✅ Created {len(herds_to_create)} herds."))