from rest_framework import serializers

from .models import Plant


DEFAULT_PLANT_GROWTH_STAGES = [
    "initial",
    "vegetative",
    "flowering",
    "fruiting",
    "maturity",
]


def normalize_growth_stage_values(plant: Plant) -> list[str]:
    stages: list[str] = []

    raw_stage = (plant.growth_stage or "").replace("،", ",")
    for part in raw_stage.split(","):
        value = part.strip()
        if value and value not in stages:
            stages.append(value)

    stage_thresholds = plant.growth_profile.get("stage_thresholds", {})
    if isinstance(stage_thresholds, dict):
        for stage_name in stage_thresholds.keys():
            value = str(stage_name).strip()
            if value and value not in stages:
                stages.append(value)

    if not stages:
        stages = list(DEFAULT_PLANT_GROWTH_STAGES)

    return stages


class PlantSerializer(serializers.ModelSerializer):
    """سریالایزر خروجی / ورودی برای Plant."""

    class Meta:
        model = Plant
        fields = [
            "id",
            "name",
            "icon",
            "light",
            "watering",
            "soil",
            "temperature",
            "growth_stage",
            "planting_season",
            "harvest_time",
            "spacing",
            "fertilizer",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["id", "created_at", "updated_at"]


class PlantNameStageSerializer(serializers.Serializer):
    name = serializers.CharField()
    icon = serializers.CharField()
    growth_stages = serializers.ListField(child=serializers.CharField())
