"""
Management command to seed a fixed demo farm-data record.
Run: python manage.py seed_farm_data
"""
from uuid import UUID

from django.core.management.base import BaseCommand

from farm_data.models import PlantCatalogSnapshot, SensorData
from farm_data.services import assign_farm_plants_from_backend_ids
from location_data.models import SoilLocation
from weather.models import WeatherForecast


DEMO_FARM_UUID = UUID("11111111-1111-1111-1111-111111111111")
DEMO_LATITUDE = "50.000000"
DEMO_LONGITUDE = "50.000000"
DEMO_FARM_BOUNDARY = {
    "type": "Polygon",
    "coordinates": [[
        [49.9995, 49.9995],
        [50.0005, 49.9995],
        [50.0005, 50.0005],
        [49.9995, 50.0005],
        [49.9995, 49.9995],
    ]],
}
DEMO_SENSOR_PAYLOAD = {
    "sensor-7-1": {
        "soil_moisture": 42.3,
        "soil_temperature": 21.4,
        "soil_ph": 6.9,
        "electrical_conductivity": 1.1,
        "nitrogen": 28.0,
        "phosphorus": 14.0,
        "potassium": 19.0,
    }
}
DEMO_PLANT_NAMES = [
    "گوجه‌فرنگی",
    "خیار",
]


class Command(BaseCommand):
    help = "Seed a fixed farm-data row with farm_uuid=11111111-1111-1111-1111-111111111111."

    def handle(self, *args, **options):
        location, _ = SoilLocation.objects.get_or_create(
            latitude=DEMO_LATITUDE,
            longitude=DEMO_LONGITUDE,
            defaults={"farm_boundary": DEMO_FARM_BOUNDARY},
        )
        changed_fields = []
        if location.farm_boundary != DEMO_FARM_BOUNDARY:
            location.farm_boundary = DEMO_FARM_BOUNDARY
            changed_fields.append("farm_boundary")
        if not location.input_block_count:
            location.input_block_count = 1
            changed_fields.append("input_block_count")
        if not location.block_layout:
            location.set_input_block_count(1)
            changed_fields.extend(["input_block_count", "block_layout"])
        if changed_fields:
            location.save(update_fields=[*dict.fromkeys(changed_fields), "updated_at"])
        weather_forecast = (
            WeatherForecast.objects.filter(location=location)
            .order_by("-forecast_date", "-id")
            .first()
        )

        farm_data, created = SensorData.objects.update_or_create(
            farm_uuid=DEMO_FARM_UUID,
            defaults={
                "center_location": location,
                "weather_forecast": weather_forecast,
                "sensor_payload": DEMO_SENSOR_PAYLOAD,
            },
        )
        plants = list(
            PlantCatalogSnapshot.objects.filter(name__in=DEMO_PLANT_NAMES).order_by("name")
        )
        if plants:
            assign_farm_plants_from_backend_ids(
                farm_data,
                [plant.backend_plant_id for plant in plants],
            )

        status_text = "Created" if created else "Updated"
        weather_text = weather_forecast.id if weather_forecast else "None"
        plant_count = len(plants)
        self.stdout.write(
            self.style.SUCCESS(
                f"{status_text} farm-data {farm_data.farm_uuid} for center_location_id={location.id} weather_forecast_id={weather_text} plants={plant_count}"
            )
        )
        self.stdout.write(self.style.SUCCESS("\nDone seeding farm_data demo record."))
