from django.db import migrations, models


DEFAULT_SENSOR_KEY = "sensor-7-1"


def migrate_sensor_fields_to_payload(apps, schema_editor):
    SensorData = apps.get_model("sensor_data", "SensorData")
    field_names = [
        "soil_moisture",
        "soil_temperature",
        "soil_ph",
        "electrical_conductivity",
        "nitrogen",
        "phosphorus",
        "potassium",
    ]

    for sensor in SensorData.objects.all().iterator():
        values = {}
        for field_name in field_names:
            value = getattr(sensor, field_name, None)
            if value is not None:
                values[field_name] = value

        sensor.sensor_payload = {DEFAULT_SENSOR_KEY: values} if values else {}
        sensor.save(update_fields=["sensor_payload"])


class Migration(migrations.Migration):

    dependencies = [
        ("sensor_data", "0005_delete_sensordatahistory"),
    ]

    operations = [
        migrations.AddField(
            model_name="sensordata",
            name="sensor_payload",
            field=models.JSONField(
                blank=True,
                default=dict,
                help_text='اطلاعات سنسورها در فرمت {"sensor-7-1": {...}}',
            ),
        ),
        migrations.AddField(
            model_name="sensorparameter",
            name="sensor_key",
            field=models.CharField(
                db_index=True,
                default=DEFAULT_SENSOR_KEY,
                help_text='کلید سنسور داخل JSON مثل "sensor-7-1" یا "leaf-sensor"',
                max_length=64,
            ),
        ),
        migrations.AddField(
            model_name="sensorparameter",
            name="data_type",
            field=models.CharField(
                default="float",
                help_text="نوع داده پارامتر مثل float, int, string, bool",
                max_length=32,
            ),
        ),
        migrations.AddField(
            model_name="sensorparameter",
            name="metadata",
            field=models.JSONField(
                blank=True,
                default=dict,
                help_text="اطلاعات تکمیلی پارامتر مثل بازه مجاز، توضیح یا تنظیمات UI",
            ),
        ),
        migrations.AddField(
            model_name="parameterupdatelog",
            name="payload",
            field=models.JSONField(
                blank=True,
                default=dict,
                help_text="خلاصه تغییرات پارامتر برای audit",
            ),
        ),
        migrations.RunPython(
            migrate_sensor_fields_to_payload,
            migrations.RunPython.noop,
        ),
        migrations.RemoveField(
            model_name="sensordata",
            name="soil_moisture",
        ),
        migrations.RemoveField(
            model_name="sensordata",
            name="soil_temperature",
        ),
        migrations.RemoveField(
            model_name="sensordata",
            name="soil_ph",
        ),
        migrations.RemoveField(
            model_name="sensordata",
            name="electrical_conductivity",
        ),
        migrations.RemoveField(
            model_name="sensordata",
            name="nitrogen",
        ),
        migrations.RemoveField(
            model_name="sensordata",
            name="phosphorus",
        ),
        migrations.RemoveField(
            model_name="sensordata",
            name="potassium",
        ),
        migrations.AlterField(
            model_name="sensorparameter",
            name="code",
            field=models.CharField(
                db_index=True,
                help_text="کد پارامتر (مثلاً soil_moisture)",
                max_length=64,
            ),
        ),
        migrations.AlterModelOptions(
            name="sensorparameter",
            options={
                "ordering": ["sensor_key", "code"],
                "verbose_name": "پارامتر سنسور",
                "verbose_name_plural": "پارامترهای سنسور",
            },
        ),
        migrations.AddConstraint(
            model_name="sensorparameter",
            constraint=models.UniqueConstraint(
                fields=("sensor_key", "code"),
                name="sensor_parameter_unique_sensor_code",
            ),
        ),
    ]
