import pandas as pd
from django.core.management.base import BaseCommand
from django.utils.dateparse import parse_datetime
from apps.livestock.models import LiveStock, LiveStockType, LiveStockSpecies
from apps.herd.models import Herd
from apps.tag.models import Tag


class Command(BaseCommand):
    help = "Import livestock 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."))

        herd_cache = {h.code: h for h in Herd.objects.all()}
        type_cache = {t.name.strip(): t for t in LiveStockType.objects.all()}
        species_male = LiveStockSpecies.objects.filter(name__icontains='نر').first()
        species_female = LiveStockSpecies.objects.filter(name__icontains='ماده').first()

        livestocks_to_create = []
        skipped = 0

        for r in records:
            try:
                herd_code = str(r.get('herd_code')).strip()
                if not herd_code:
                    skipped += 1
                    continue

                herd = herd_cache.get(herd_code)
                if not herd:
                    herd = Herd.objects.create(
                        code=herd_code,
                        name=f"گله {herd_code}",
                        province_id=int(r.get('province_id')) if r.get('province_id') else None,
                        city_id=int(r.get('city_id')) if r.get('city_id') else None,
                        cooperative_id=int(r.get('cooperative_id')) if r.get('cooperative_id') else None,
                    )
                    herd_cache[herd_code] = herd

                tag_code = r.get('national_id_livestock_code')
                tag = Tag.objects.filter(code=tag_code).first()
                if not tag:
                    skipped += 1
                    continue

                type_name = str(r.get('type')).strip()
                livestock_type = type_cache.get(type_name)
                if not livestock_type:
                    skipped += 1
                    continue

                gender_str = str(r.get('gender')).strip()
                gender = 1 if gender_str == 'نر' else 2 if gender_str == 'ماده' else None
                species = species_male if gender == 1 else species_female

                birthdate = parse_datetime(str(r.get('birth_day_gh'))) if r.get('birth_day_gh') else None
                weight_type = 'H' if type_name == 'گاو' else 'L'

                livestocks_to_create.append(LiveStock(
                    herd=herd,
                    tag=tag,
                    type=livestock_type,
                    use_type=None,
                    species=species,
                    weight_type=weight_type,
                    gender=gender,
                    birthdate=birthdate
                ))

            except Exception as e:
                skipped += 1
                print(e)
                continue

        LiveStock.objects.bulk_create(livestocks_to_create, batch_size=10000)

        self.stdout.write(self.style.SUCCESS(f"✅ Created {len(livestocks_to_create)} records."))
        self.stdout.write(self.style.WARNING(f"⚠️ Skipped {skipped} records due to missing/invalid data."))
