import { defineStore } from 'pinia';
import router from '@/router'; // Adjust the import based on your router setup
import axios from 'axios';

export const usePlantStateStore = defineStore('plantState', {
  state: () => ({
    imageResult: null,
    textResult: null,
    plantDataDescription: '',
    conditionDataDescription: '',
    imageBase64: null,
    plantHealthDescription: '',
    generatedImageBase64: null,
    plantData: {
      plant_characteristics: {
        morphological: {
          plant_type: '',
          height: 0,
          leaf_color: '',
          presence_of_flowers: false,
          fruit_development: false,
          root_health: ''
        },
        physiological: {
          health_status: '',
          growth_rate: 0,
          photosynthesis_rate: 0,
          transpiration_rate: 0
        }
      }
    },
    conditionData: {
      environmental_characteristics: {
        atmosphere: {
          air_temperature: 20,
          relative_humidity: 50,
          co2_concentration: 400,
          air_pressure: 101.3,
          wind_speed: 0
        },
        soil: {
          soil_temperature: 20,
          soil_acidity: 6.5,
          soil_moisture: 50,
          nutrients: []
        },
        light: {
          light_intensity: 500,
          photoperiod: 12
        },
        water: {
          watering_frequency: 3
        }
      }
    },
    time_period: '',
    cure: '',
    text_response: '',
    health: {
      health_breakdown: {
        Dead: 0.0105,
        Dehydrated: 0.0421,
        Diseased: 0.0562,
        Healthy: 0.8912
      },
      health_status: "Healthy",
    }
  }),
  actions: {
    async healthCheck() {
      // Convert base64 to Blob (File is a specialized Blob)
      const blob = await fetch(this.imageBase64).then(res => res.blob());

      // Create a File object from the Blob
      const imageFile = new File([blob], 'image', { type: 'image/jpeg' });

      // Create FormData and append the file
      const formData = new FormData();
      formData.append('image', imageFile);

      const res = await axios.post('/api/analyze', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Access-Control-Allow-Origin': '*'
        }
      });

      function makePercentage(number) {
        // Ensure the number is between 0 and 1
        if (number < 0 || number > 1) {
          throw new Error("Number must be between 0 and 1");
        }

        // Convert to percentage and return as a string
        return (number * 100).toFixed();
      }

      this.health.health_breakdown.Dead = makePercentage(res.data.health_breakdown.Dead);
      this.health.health_breakdown.Dehydrated = makePercentage(res.data.health_breakdown.Dehydrated);
      this.health.health_breakdown.Diseased = makePercentage(res.data.health_breakdown.Diseased);
      this.health.health_breakdown.Healthy = makePercentage(res.data.health_breakdown.Healthy);
      this.health.health_status = res.data.health_status;

      this.plantData.plant_characteristics.morphological.plant_type = res.data.plant_species;
    },
    setPlantData(data) {
      this.plantData = {
        plant_characteristics: {
          ...this.plantData.plant_characteristics,
          ...data.plant_characteristics
        }
      };
    },
    setConditionData(data) {
      this.conditionData = {
        environmental_characteristics: {
          ...this.conditionData.environmental_characteristics,
          ...data.environmental_characteristics
        }
      };
    },
    async sendRequest() {
      await router.push('/loading')

      const data = {
        plant_state_description: this.plantDataDescription,
        plant_state_details: this.plantData,
        environmental_changes_description: this.conditionDataDescription,
        environmental_changes_details: this.conditionData,
        time_period: this.time_period
      }

      const res = await axios.post('http://localhost:3000/analyze', JSON.stringify(data), {
        headers: {
          'Content-Type': 'application/json'
        }
      });

      const imageRes = await axios.post('http://localhost:3000/generate', JSON.stringify([res.data.result.image_generator_prompt, this.imageBase64]), {
        headers: {
          'Content-Type': 'application/json'
        }
      });

      console.log('Image generation prompt:', res.data.result.image_generator_prompt);

      this.generatedImageBase64 = imageRes.data.result;

      this.text_response = res.data.result.final_description_text;
      await router.push('/results');
    },
    async askForCure() {

      const res = await axios.post('http://localhost:3000/cure', JSON.stringify({
        plant_state_description: this.plantDataDescription,
        plant_state_details: this.plantData,
        time_period: this.time_period
      }), {
        headers: {
          'Content-Type': 'application/json'
        }
      });

      this.cure = res.data.result;
    },
    setImage(base64) {
      this.imageBase64 = base64
      localStorage.setItem('uploadedImage', base64)
    },
  }
});
