from __future__ import annotations from datetime import date from plant.gdd import predict_harvest_from_forecasts def _harvest_language(prediction: dict, plant_name: str, ai_bundle: dict | None = None) -> str: ai_bundle = ai_bundle or {} ai_payload = ai_bundle.get("harvestPredictionCard", {}) if isinstance(ai_bundle, dict) else {} description = ai_payload.get("description") if isinstance(description, str) and description.strip(): return description.strip() return ( f"برای {plant_name}، رشد تجمعی بر اساس مدل GDD محاسبه شده است. " f"تا امروز {prediction['current_cumulative_gdd']} واحد-روز رشد ثبت شده و " f"برای رسیدن به بلوغ حدود {prediction['remaining_gdd']} واحد-روز دیگر نیاز است." ) def build_harvest_prediction_card(sensor_id: str, context: dict | None = None, ai_bundle: dict | None = None) -> dict: context = context or {} forecasts = context.get("forecasts", []) plants = context.get("plants", []) plant = plants[0] if plants else None plant_name = plant.name if plant else "محصول" prediction = predict_harvest_from_forecasts(forecasts=forecasts, plant=plant).__dict__ target_date = date.fromisoformat(prediction["predicted_harvest_date"]) window_start = date.fromisoformat(prediction["predicted_harvest_window"]["start"]) window_end = date.fromisoformat(prediction["predicted_harvest_window"]["end"]) return { "date": prediction["predicted_harvest_date"], "dateFormatted": f"{target_date.day} {target_date.strftime('%B')} {target_date.year}", "daysUntil": prediction["estimated_days_to_harvest"], "description": _harvest_language(prediction, plant_name=plant_name, ai_bundle=ai_bundle), "optimalWindowStart": window_start.isoformat(), "optimalWindowEnd": window_end.isoformat(), "gddDetails": prediction, }