"""
Management command to seed the 7 initial sensor parameters.
Run: python manage.py seed_sensor_parameters
"""
from django.core.management.base import BaseCommand

from farm_data.models import (
    DEFAULT_SENSOR_DATA_TYPE,
    DEFAULT_SENSOR_KEY,
    ParameterUpdateLog,
    SensorParameter,
)


INITIAL_PARAMETERS = [
    ("soil_moisture", "رطوبت خاک", "%"),
    ("soil_temperature", "دما خاک", "°C"),
    ("soil_ph", "pH خاک", ""),
    ("electrical_conductivity", "هدایت الکتریکی", "dS/m"),
    ("nitrogen", "ازت (N)", "mg/kg"),
    ("phosphorus", "فسفر", "mg/kg"),
    ("potassium", "پتاسیم", "mg/kg"),
]


class Command(BaseCommand):
    help = "Seed 7 initial sensor parameters (soil_moisture, soil_temperature, etc.)"

    def add_arguments(self, parser):
        parser.add_argument(
            "--sensor-key",
            default=DEFAULT_SENSOR_KEY,
            help='کلید سنسور مثل "sensor-7-1" یا "leaf-sensor"',
        )

    def handle(self, *args, **options):
        sensor_key = options["sensor_key"]
        created_count = 0
        for code, name_fa, unit in INITIAL_PARAMETERS:
            param, created = SensorParameter.objects.get_or_create(
                sensor_key=sensor_key,
                code=code,
                defaults={
                    "name_fa": name_fa,
                    "unit": unit,
                    "data_type": DEFAULT_SENSOR_DATA_TYPE,
                },
            )
            if created:
                ParameterUpdateLog.objects.create(
                    parameter=param,
                    action="added",
                    payload={
                        "sensor_key": sensor_key,
                        "code": code,
                        "name_fa": name_fa,
                        "unit": unit,
                    },
                )
                created_count += 1
                self.stdout.write(
                    self.style.SUCCESS(
                        f"  Created: {sensor_key}.{code} ({name_fa})"
                    )
                )
        self.stdout.write(
            self.style.SUCCESS(
                f"\nDone. Created {created_count} new parameters for {sensor_key}."
            )
        )
