using ReAct_PME.WPF_FrameWork;
using Services.Models;
using Services.Ollama;
using Services.ReActAgent;
using System.Collections.ObjectModel;
using ToolsServices;

namespace ReAct_PME.ViewModels
{
    public class ParametresModeles_VM : BaseViewModel
    {
        private ModelsUseCases.TypeUseCase UseCase;
        private ReActAgent Agent;

        //public ParametresOllamaService SelectedItem { get; set; } = new();
        public ObservableCollection<OllamaModel> InstalledModels { get; set; } = new();
        public ModelConfig SelectedItem { get; set; } = new();

        public ParametresModeles_VM(ModelsUseCases.TypeUseCase useCase)
        {
            UseCase = useCase;
            Agent = new ReActAgent();
            GetInstalledModels();
        }

        public bool SaveData()
        {
            try
            {
                return ReActAgent.SaveParametresModeles(UseCase, SelectedItem);
            }
            catch
            {
                return false;
            }

        }

        private async void GetInstalledModels()
        {
            await GetInstalledModelsAsync();
            GetModelsByUseCase();
        }

        private void GetModelsByUseCase()
        {
            var models = ReActAgent.GetModelesIA(UseCase);
            if(models != null)
            {
                var modelsLst= models.ToList();
                if (modelsLst.Count > 0)
                    SelectedItem.Primary = modelsLst[0];
                if (modelsLst.Count > 1)
                    SelectedItem.Secondary = modelsLst[1];
                if (modelsLst.Count > 2)
                    SelectedItem.Fallback = modelsLst[2];

                OnPropertyChanged(nameof(SelectedItem));
            }
        }

        private async Task GetInstalledModelsAsync()
        {
            try
            {
                bool isOnDemand = (UseCase != ModelsUseCases.TypeUseCase.AnalyseMails);
                var installedModels = await Agent.GetInstalledModelsAsync(isOnDemand);
                InstalledModels.Clear(); //  Utiliser la propriété
                foreach (var model in installedModels)
                    InstalledModels.Add(model);
                OnPropertyChanged(nameof(InstalledModels));
            }
            catch (Exception ex)
            {
                LoggerService.LogError($"Erreur lors de la récupération des modèles installés : {ex.Message}");
            }
        }

    }
}
