using MaterialDesignThemes.Wpf;
using ReAct_PME.WPF_FrameWork;
using Service;
using Services;
using Services.ReActAgent;
using System.Speech.Recognition;
using System.Text.Json;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using ToolsServices;
using UI.Services;

namespace ReAct_PME
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string NUM_VERSION = "1.1.1";
        private string DATE_VERSION = new DateTime(2025,11,19).Date.ToShortDateString();

        #region Variables
        private readonly DispatcherTimer _Timer;
        private bool IsOllamaActif = false;
        private bool IsOllamaBatchActif = false;
        private bool IsOkToCheckEmails = false;
        private bool IsFirstVerif = true;
        private SpeechService Speech = new(4,50);

        #endregion

        #region Constructeur
        public MainWindow()
        {
            InitializeComponent();

#if DEBUG 
            this.Title += " - DEV"; 
#endif

            LoggerService.LogInfo("Application démarrée");

            VerifLicence();

            BtnParler.IsEnabled = true;
            BtnStopParler.IsEnabled = false;

            _Timer = new DispatcherTimer();
            _Timer.Interval = TimeSpan.FromSeconds(3600);
            _Timer.Tick += async (s, e) => await VerifServices();
            _Timer.Start();

            //LoggerService.LoadParametres();
            FichiersInternesService.VerifPath();

            _ = VerifServices();
            LoggerService.PurgeLogs();

            BtnParler.Visibility = Visibility.Collapsed;
            BtnStopParler.Visibility = Visibility.Collapsed;

            //TestPptx();
            LoggerService.LogInfo("Application prête");

            FaceRecognition.FaceRecognitionService o = new(true);
            try
            {
                var lst = o.PredictLiveNoShow();
                string lstSTR = string.Join(", ", lst);
                if (lstSTR == "")
                {
                    lstSTR = "utilisateur inconnu";
                    ToolsServices.LoggerService.LogInfo($"La reconnaissance faciale a échouée");
                }
                else
                {
                    ToolsServices.LoggerService.LogInfo($"La reconnaissance faciale a réussie pour {lstSTR}");
                }
                TxtMessageNom.Text = $"Bonjour {lstSTR}";
                
            }
            catch
            {

            }
        }
        #endregion


        private void ButtonWhoIAm_Click(object sender, RoutedEventArgs e)
        {
            FaceRecognition.FaceRecognitionService o = new(true);
            try
            {
                var lst = o.PredictLiveNoShow();
                string lstSTR = string.Join(", ", lst);
                if (lstSTR == "")
                {
                    lstSTR = "utilisateur inconnu";
                    ToolsServices.LoggerService.LogInfo($"La reconnaissance faciale a échouée");
                }
                else
                {
                    ToolsServices.LoggerService.LogInfo($"La reconnaissance faciale a réussie pour {lstSTR}");
                }
                TxtMessageNom.Text = $"Bonjour {lstSTR}";
            }
            catch
            {

            }
        }

        #region Méthodes privées communes
        private void SaisirLicence_Click()
        {
            if (System.IO.File.Exists(ToolsServices.FichiersInternesService.ParamsLicence))
                System.IO.File.Delete(ToolsServices.FichiersInternesService.ParamsLicence);

            VerifLicence();
        }

        private void VerifLicence()
        {
            AfficheMenus(false, 0);

            // Quelque soit la chaine saisie ou trouvée, on ne prend que les 2 derniers caractères qui doivent être numériques.
            var last2 = "";
            var licence = ToolsServices.TxtService.ExtractTextFromTxt(ToolsServices.FichiersInternesService.ParamsLicence);
            if(licence == null || licence == "")
            {
                var box = new InputBox("Quel est le code de la lience?", "Code licence requise", "0");
                bool? result = box.ShowDialog();
                if (result == true)
                {
                    string valeur = box.Response;
                    if (valeur.Length < 2)
                    {
                        MessageBox.Show("Valeur incorrecte.");
                        return;
                    }

                    last2 = valeur.Substring(valeur.Length - 2, 2);
                    var b = int.TryParse(last2, out int returnValeur);
                    if (b)
                    {
                        licence = last2;
                        ToolsServices.TxtService.CreateTextFile(ToolsServices.FichiersInternesService.ParamsLicence, valeur);
                    }
                    else
                    {
                        MessageBox.Show("Valeur incorrecte.");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("Action annulée.");
                    return;
                }
            }
            else
            {
                last2 = licence.Substring(licence.Length - 2, 2);
                var b = int.TryParse(last2, out int returnValeur);
                if(!b)
                {
                    MessageBox.Show("Valeur trouvée incorrecte.");
                    return;
                }
            }

            AfficheMenus(true, int.Parse(last2));
        }

        public static (int v1, int v2, int v3, int v4) Decompose(int somme)
        {
            int v1 = (somme & 1) > 0 ? 1 : 0;   // bit 0 → 1ère valeur
            int v2 = (somme & 2) > 0 ? 2 : 0;   // bit 1 → 2ème valeur
            int v3 = (somme & 4) > 0 ? 4 : 0;   // bit 2 → 3ème valeur
            int v4 = (somme & 8) > 0 ? 8 : 0;   // bit 3 → 4ème valeur

            return (v1, v2, v3, v4);
        }

        private void AfficheMenus(bool isVisible, int valeur=0)
        {
            var (valeur1, valeur2, valeur3, valeur4) = Decompose(valeur);

            // Menu CHAT et ses paramètres
            if (!isVisible || valeur1 > 0)
            {
                this.Mnu_Chat.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresRAG.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresGenerationImages.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresFooocus.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresQdrant.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;

                FooocusIcone.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                FooocusStatus.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                TxtFooocusStatus.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;

                QdrantIcone.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                QdrantStatus.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                TxtQdrantStatus.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
            }

            // Menu CV et ses paramètres
            if (!isVisible || valeur2 > 0)
            { 
                this.Mnu_CV.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed; 
            }

            // Menu MAILS et ses paramètres
            if (!isVisible || valeur3 > 0)
            { 
                this.Mnu_Mails.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresCompteMail.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresCheckMails.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresQdrant.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;

                QdrantIcone.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                QdrantStatus.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                TxtQdrantStatus.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
            }

            // Menu DOCUMENTS ENTREPRISE et ses paramètres
            if (!isVisible || valeur4 > 0)
            { 
                this.Mnu_Documents.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresFactures.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresWhisper.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                this.Mnu_ParametresTF_From_DSF.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;

                WhisperIcone.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                WhisperStatus.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
                TxtWhisperStatus.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;

            }
        }

        private void LancerCheckEmails()
        {
            if (IsOllamaActif && !IsOkToCheckEmails)
            {
                var (rep1, rep2) = Services.EmailService.LoadParametresCheckEmail();
                if(rep1 == 1)
                {
                    AnalyseEmailsInbox();
                }
                if (rep2 == 1)
                {
                    AnalyseEmailsSent();
                }
                IsOkToCheckEmails = true;
            }

}
        
        private void Notifications()
        {

                string Pluriel(int n, string mot) => n > 1 ? $"{mot}s" : mot;
                var annonce = "";
                var annonceSpeech = "";
                var parametresUser = Services.EmailService.LoadParametres();
                var overdueDelay = 7;
                if (parametresUser != null)
                {
                    overdueDelay = parametresUser.OverdueDaysSent;
                }
                var nb = EmailSendService.NbRelancesEnAttente();
                if (nb > 0)
                {
                    var txt = $"⚠ Vous avez {nb} {Pluriel(nb, "relance")} en attente depuis + de {overdueDelay} {Pluriel(overdueDelay, "jour")}\n\n";
                    annonce += txt;
                    annonceSpeech += txt;
                }

                var ListeItems = Services.EmailService.ChargerEmailsDepuisJson();
                int total = ListeItems!.Count;
                if (total > 0)
                {
                    int importants = ListeItems.Count(e => e.IsImportant && !e.IsUrgent);
                    int urgents = ListeItems.Count(e => e.IsUrgent && !e.IsImportant);
                    int urgentsEtImportants = ListeItems.Count(e => e.IsUrgent && e.IsImportant);

                    var txtImportantUrgent = $"\nVous avez {urgentsEtImportants} {Pluriel(urgentsEtImportants, "mail")} non lus {Pluriel(urgentsEtImportants, "important et urgent")}";

                    var txt = $"⚠ Vous avez {total} mail{(total > 1 ? "s" : "")} non lu{(total > 1 ? "s" : "")} dont : " +
                           $"\n ✓ {urgentsEtImportants} {Pluriel(urgentsEtImportants, "important et urgent")}" +
                           $"\n ✓ {importants} {Pluriel(importants, "important")}, " +
                           $"\n ✓ {urgents} {Pluriel(urgents, "urgent")}";
                    annonce += txt;
                    annonceSpeech += txtImportantUrgent;
                }

                TxtAnnonce.Text = annonce;
                annonce += $"\n -- Mise à jour : {DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}"; ;
                if (annonceSpeech.Length > 0 && IsFirstVerif)
                {
                    annonceSpeech = annonceSpeech.Replace("⚠ ", "");
                    annonceSpeech = annonceSpeech.Replace("✓ ", "");

                    Speech.Lire(annonceSpeech);
                }
            
        }
        
        private async Task VerifServices()
        {
            Notifications();

            #region RAZ
            MenusDisabled(false, false, false);

            txtOllamaStatus.Text = "Vérification de l'Assistant d'analyse OnDemand";
            txtOllamaBatchStatus.Text = "Vérification de l'Assistant d'analyse Batch";
            TxtFooocusStatus.Text = "Vérification de l'Assistant créatif";
            TxtWhisperStatus.Text = "Vérification de l'Assistant transcribe";
            TxtQdrantStatus.Text = "Vérification de l'Assistant vectoriel";

            txtOllamaStatus.Foreground = Brushes.Gray;
            txtOllamaBatchStatus.Foreground = Brushes.Gray;
            TxtFooocusStatus.Foreground = Brushes.Gray;
            TxtWhisperStatus.Foreground = Brushes.Gray;
            TxtQdrantStatus.Foreground = Brushes.Gray;

            SetEllipseColor(OllamaStatus, false, true);
            SetEllipseColor(OllamaBatchStatus, false, true);
            SetEllipseColor(FooocusStatus, false, true);
            SetEllipseColor(WhisperStatus, false, true);
            SetEllipseColor(QdrantStatus, false, true);
            #endregion

            #region Ollama OnDemand
            bool b1 = await ReActAgent.IsOllamaActif(true);
            IsOllamaActif = b1;
            //SetEllipseColor(OllamaStatus, b1, false);

            if (!b1)
            {
                AnimateStatus(OllamaStatus, Colors.Gray, Colors.Red);
                txtOllamaStatus.Text = "Assistant d'analyse OnDemand indisponible.";
                txtOllamaStatus.Foreground = Brushes.Red;
            }
            else
            {
                AnimateStatus(OllamaStatus, Colors.Gray, Colors.Green);
                txtOllamaStatus.Text = "Assistant d'analyse OnDemand en ligne";
                txtOllamaStatus.Foreground = Brushes.Green;
            }
            #endregion

            #region Ollama Batch
            bool b2 = await ReActAgent.IsOllamaActif(false);
            IsOllamaBatchActif = b2;
            SetEllipseColor(OllamaBatchStatus, b2, false);
            if (!b2)
            {
                AnimateStatus(OllamaBatchStatus, Colors.Gray, Colors.Red); 
                txtOllamaBatchStatus.Text = "Assistant d'analyse Batch indisponible.";              
                txtOllamaBatchStatus.Foreground = Brushes.Red;
            }
            else
            {
                AnimateStatus(OllamaBatchStatus, Colors.Gray, Colors.Green); 
                txtOllamaBatchStatus.Text = "Assistant d'analyse Batch en ligne";
                txtOllamaBatchStatus.Foreground = Brushes.Green;
                
                // Lancer (ou pas) le check des emails au démarrage de l'appli (uniquement)
                if (IsFirstVerif)
                {
                    LancerCheckEmails();
                    IsFirstVerif = false;
                }
            }
            #endregion

            #region Fooocus
            bool b3 = await ReActAgent.IsFooocusActif();
            //SetEllipseColor(FooocusStatus, b3, false);

            if (!b3)
            {
                TxtFooocusStatus.Text = "Assistant créatif indisponible.";
                TxtFooocusStatus.Foreground = Brushes.Red;
                AnimateStatus(FooocusStatus, Colors.Gray, Colors.Red);
            }
            else
            {
                AnimateStatus(FooocusStatus, Colors.Gray, Colors.Green);
                TxtFooocusStatus.Text = "Assistant créatif en ligne";
                TxtFooocusStatus.Foreground = Brushes.Green;
            }
            #endregion

            #region Whisper
            bool b4 = await ReActAgent.IsWhisperActif();
            if (!b4)
            {
                AnimateStatus(WhisperStatus, Colors.Gray, Colors.Red);
                TxtWhisperStatus.Text = "Assistant transcribe indisponible.";
                TxtWhisperStatus.Foreground = Brushes.Red;
            }
            else 
            { 
                AnimateStatus(WhisperStatus, Colors.Gray, Colors.Green);
                TxtWhisperStatus.Text = "Assistant transcribe en ligne";
                TxtWhisperStatus.Foreground = Brushes.Green;
            }
            #endregion

            #region Qdrant
            QdrantService qdrant = new();
            bool b5 = await qdrant.IsAlive();
            if (!b5)
            {
                AnimateStatus(QdrantStatus, Colors.Gray, Colors.Red);
                TxtQdrantStatus.Text = "Assistant vectoriel indisponible.";
                TxtQdrantStatus.Foreground = Brushes.Red;
            }
            else
            {
                AnimateStatus(QdrantStatus, Colors.Gray, Colors.Green);
                TxtQdrantStatus.Text = "Assistant vectoriel en ligne";
                TxtQdrantStatus.Foreground = Brushes.Green;
            }

            #endregion

            MenusDisabled(b1, b2, b3);

        }


        private void AnimateStatus(Ellipse target, Color fromColor, Color toColor)
        {
            var brush = new SolidColorBrush(fromColor);
            target.Fill = brush;

            var colorAnimation = new ColorAnimation
            {
                From = fromColor,
                To = toColor,
                Duration = TimeSpan.FromSeconds(1.0)
            };

            brush.BeginAnimation(SolidColorBrush.ColorProperty, colorAnimation);
        }

        private void MenusDisabled(bool isOllamaActif, bool isOllamaBatchActif, bool isFooocusActif)
        {
            #region Paramètres / modèles
            Mnu_paramModeles.IsEnabled = isOllamaActif;
            #endregion

            #region Gestion des mails
            var param = Services.EmailService.LoadParametres();
            Mnu_ListeMails.IsEnabled = (param != null && param.IsOk && isOllamaBatchActif);
            Mnu_ListeMailsSend.IsEnabled = (param != null && param.IsOk && isOllamaBatchActif);
            Mnu_GenerateMail.IsEnabled = (param != null && param.IsOk && isOllamaActif);
            #endregion

            #region CV
            Mnu_RechercheCV.IsEnabled = isOllamaActif;
            Mnu_GenererCV.IsEnabled = isOllamaActif;
            #endregion

            #region Documents d'entreprises
            Mnu_Factures_PDF_to_XML.IsEnabled = isOllamaActif;
            Mnu_MakeTF_From_DSF.IsEnabled = isOllamaActif;
            Mnu_ResumeAudio.IsEnabled = isOllamaActif;
            #endregion

            #region ChatRoom
            Mnu_CHAT_LLM.IsEnabled = isOllamaActif;
            Mnu_CHAT_RAG.IsEnabled = isOllamaActif;
            Mnu_CHAT_LLM_CODER.IsEnabled = isOllamaActif;

            Mnu_CHAT_GenerateImg.IsEnabled = false;
            if (System.IO.File.Exists(FichiersInternesService.ParamsGenerateImg))
            {
                var txt = System.IO.File.ReadAllText(FichiersInternesService.ParamsGenerateImg);
                if (txt.Trim().Length > 0)
                {
                    Mnu_CHAT_GenerateImg.IsEnabled = (true && isFooocusActif);
                }
            }
            #endregion 
        }

        private void SetEllipseColor(System.Windows.Shapes.Ellipse ellipse, bool isAlive, bool isStandby)
        {
            ellipse.Fill = isAlive ? Brushes.Green : isStandby ? Brushes.Gray : Brushes.Red;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            LoggerService.LogInfo("Application fermée");
        }

        private async void ButtonRefresh_Click(object sender, RoutedEventArgs e)
        {
            await VerifServices();
        }

        private void ButtonQuit_Click(object sender, RoutedEventArgs e)
        {
            foreach (Window window in System.Windows.Application.Current.Windows)
            {
                if (window != this) // si tu veux garder la fenêtre principale ouverte
                {
                    window.Close();
                }
            }
            this.Close();
        }
        #endregion

        #region Documents d'entreprises
        
        private void BtnResumeAudio_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ResumeAudio");
            var f = new ResumeAudio();
            f.Show();
        }

        private void BtnMakeTF_From_DSF_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir MakeTF_From_DSF_Click");
            var f = new ParametresTF_From_DSF(true);
            f.Show();
        }

        private void BtnFactures_PDF_to_XML_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir Factures_PDF_to_XML_Click");
            var f = new ParametresFactures(true);
            f.Show();
        }
        #endregion 

        #region Mails

        private void AnalyseEmailsInbox()
        {
            LoggerService.LogInfo("Ouvrir ListeEmails");
            var f = new ListeEmails();
            f.Show();
        }

        private void AnalyseEmailsSent()
        {
            LoggerService.LogInfo("Ouvrir ListeEmailsSend");
            var f = new ListeEmailsSend();
            f.Show();
        }

        private void BtnGenerateEmail_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir GenerateEmail");
            var f = new GenerateEmail();
            f.Show();
        }

        private void BtnListeEmails_Click(object sender, RoutedEventArgs e)
        {
            AnalyseEmailsInbox();
        }

        private void BtnListeEmailsSend_Click(object sender, RoutedEventArgs e)
        {
            AnalyseEmailsSent();
        }

        #endregion

        #region CV

        private void BtnRechercheCV_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir RechercheCV");
            var f = new RechercheCV();
            f.Show();
        }

        private void BtnGenererCV_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir GenererCV");
            var f = new GenererCV();
            f.Show();
        }

        #endregion

        #region Chat-room

        private void BtnChatRoom_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Chat Room - LLM");
            var f = new ChatRoom(false, false, false);
            f.Show();
        }
        private void BtnRAG_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Chat Room - RAG");
            var f = new ChatRoom(true, false, false);
            f.Show();
        }
        
        private void BtnGenerateImg_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Chat Room - Generate Image");
            var f = new ChatRoom(false, true, false);
            f.Show();
        }

        private void BtnChatRoomCoder_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Chat Room - Coder");
            var f = new ChatRoom(false, false, true);
            f.Show();
        }
        #endregion

        #region Paramètres

        #region Prompts
        private void BtnParametresPrompts_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresPrompts");
            var f = new ParametresPrompts();
            f.ShowDialog();
        }
        #endregion

        #region Modèles
        private void BtnParametresModelesLLM_Coder_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesLLM_Coder");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.LLM_Coder);
            f.ShowDialog();
        }
        private void BtnParametresModelesMakeTF_From_DSF_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesMakeTF_From_DSF");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.TF_From_DSF);
            f.ShowDialog();
        }

        private void BtnParametresModelesLLM_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesLLM");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.LLM);
            f.ShowDialog();
        }

        private void BtnParametresModelesAnalyseMails_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesAnalyseMails");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.AnalyseMails);
            f.ShowDialog();
        }

        private void BtnParametresModelesGenerationMails_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesGenerationMails");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.GenerationMail);
            f.ShowDialog();
        }
        //
        private void BtnParametresModelesAnalyseCVMission_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesAnalyseCVMission");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.AnalyseCVMission);
            f.ShowDialog();
        }

        private void BtnParametresModelesCV_to_XML_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesCV_to_XML");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.CV_To_Xml);
            f.ShowDialog();
        }

        private void BtnParametresModelesRAG_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesRAG");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.RAG);
            f.ShowDialog();
        }

        private void BtnParametresModelesResumeDocuments_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesResumeDocuments");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.ResumeDocuments);
            f.ShowDialog();
        }

        private void BtnParametresModelesInterpretationImages_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesInterpretationImages");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.InterpretationImages);
            f.ShowDialog();
        }

        private void BtnParametresModelesPromptGenerationFooocus_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesPromptGenerationFooocus");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.PromptGenerationFooocus);
            f.ShowDialog();
        }

        private void BtnParametresModelesPdfToXml_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresModelesPdfToXml");
            var f = new ParametresModeles(ModelsUseCases.TypeUseCase.Facture_To_Xml);
            f.ShowDialog();
        }

        #endregion

        #region Autres

        
        private void BtnParametresFaceRecognition_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir BtnParametresFaceRecognition");

            var f = new ParametresFaceRecognition();
            f.Show();
        }

        private void BtnParametresTF_From_DSF_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir BtnParametresTF_From_DSF");

            var f = new ParametresTF_From_DSF(false);
            f.Show();
        }

        private void BtnParametresFactures_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir BtnParametresFactures");

            var f = new ParametresFactures(false);
            f.Show();
        }

        private void BtnParametresFooocus_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir BtnParametresFooocus");
            
            var f = new ParametresFooocus();
            f.Show();            
        }
        //
        private void BtnParametresWhisper_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir BtnParametresWhisper");

            var f = new ParametresWhisper();
            f.Show();
        }

        private void BtnParametresGenerateImg_Click(object sender, RoutedEventArgs e)
        {          
            LoggerService.LogInfo("Ouvrir ParametresGenerationImages");

            var f = new ParametresGenerateImg();
            f.ShowDialog();
            
            var (url, endpointv1, endpointv2) = ChatService.LoadParametresGenerateImg();
            Mnu_CHAT_GenerateImg.IsEnabled = (url.Trim().Length > 0 && endpointv1.Trim().Length>0);
        }

        private void BtnParametresCompteMail_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresCompteMail");
            var f = new ParametresCompteMail();
            f.ShowDialog();
            var param = Services.EmailService.LoadParametres();
            Mnu_ListeMails.IsEnabled = !(param == null || !param.IsOk);
        }

        private void BtnParametresCheckMail_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresCheckMail");
            var f = new ParametresCheckEmails();
            f.ShowDialog();
        }

        private void BtnParametresRAG_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresRAG");
            var f = new ParametresRAG();
            f.ShowDialog();
        }

        private void BtnParametresQdrant_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresQdrant");
            var f = new ParametresQdrant();
            f.ShowDialog();
        }

        private void BtnParametresOllama_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresOllama");
            var f = new ParametresOllama();
            f.ShowDialog();
        }

        private void BtnParametresLogs_Click(object sender, RoutedEventArgs e)
        {
            LoggerService.LogInfo("Ouvrir ParametresLogs");
            var f = new ParametresLogs();
            f.ShowDialog();
        }
        #endregion

        #endregion

        #region Aide

        private void VoirLogs_Click(object sender, RoutedEventArgs e)
        {
            var f = new VoirLogs();
            f.ShowDialog();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var txt = "Pour une utilisation à distance, Ollama doit être lancé : \r\n $env:OLLAMA_HOST=\"0.0.0.0\" (ou aller dans les paramètres de Ollama et cocher \"Expose Ollama to the Network\") \r\n puis ollama serve.";

            NotificationManager.ShowNotification(txt, "Lancement Ollama");
        }

        private void APropos_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.MessageBox.Show($"AIT - Tous droits réservés\nVersion {NUM_VERSION} du {DATE_VERSION}","Agent ReAct PME");
        }

        
        private void WhoIAmTest_Click(object sender, RoutedEventArgs e)
        {
            FaceRecognition.FaceRecognitionService o = new(true);
            var parametres = FaceRecognition.FaceRecognitionService.LoadParametres();
            try
            {
                var path = parametres.Path_TestSet;
                o.Predict(System.IO.Path.Combine(path, "Sonia_20251020_190530.jpg"));
                o.Predict(System.IO.Path.Combine(path, "Capture.JPG"));
                o.Predict(System.IO.Path.Combine(path, "AIT.jpg"));
                o.Predict(System.IO.Path.Combine(path, "AIT_6.jpg"));

            }
            catch
            {

            }
        }

        private void WhoIAmPredictLive_Click(object sender, RoutedEventArgs e)
        {
            FaceRecognition.FaceRecognitionService o = new(true);
            try
            {
                o.PredictLive();
            }
            catch 
            {

            }
        }

        private void WhoIAmTraining_Click(object sender, RoutedEventArgs e)
        {
            FaceRecognition.FaceRecognitionService o = new(true);
            try
            {
                var (b,s) = o.Training(false);
                if(b)
                    MessageBox.Show("Entraînement terminé !","Succès");
                else
                    MessageBox.Show($"{s}", "Entraînement terminé avec des erreurs", MessageBoxButton.OK, MessageBoxImage.Error);

            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex.Message}", "Entraînement terminé avec des erreurs", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        

        private void WhoIAmPhoto_Click(object sender, RoutedEventArgs e)
        {
            var f = new CapturePhoto();
            f.Show();
        }

        private void SaisirLicence_Click(object sender, RoutedEventArgs e)
        {
            SaisirLicence_Click();
        }
  
        private void Quitter_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        #endregion

        static void TestPptx()
        {
            // Exemple JSON simulant la sortie d’Ollama
            string json = @"[
                  {""Title"": ""Introduction à l'IA"", ""Content"": ""Définition et contexte""},
                  {""Title"": ""Applications"", ""Content"": ""Santé, finance, industrie, divertissement""},
                  {""Title"": ""Avantages et limites"", ""Content"": ""Automatisation, gain de temps, risques éthiques""},
                  {""Title"": ""Conclusion"", ""Content"": ""Résumé et perspectives futures""}
                ]";

            var slides = JsonSerializer.Deserialize<List<SlideData>>(json);

            PowerPointGenerator.CreatePpt(@"D:\_TrainingData\presentation.pptx", slides);

            LoggerService.LogDebug("✅ Fichier PowerPoint généré : presentation.pptx");
        }

        #region Tests en cours - Parler / Ecouter
        private void BtnParler_Clickold(object sender, RoutedEventArgs e)
        {
            BtnParler.IsEnabled = false;
            BtnStopParler.IsEnabled = true;

            Speech.Parler();

        }

        private void BtnParler_Click(object sender, RoutedEventArgs e)
        {
            using (SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine())
            {
                recognizer.SetInputToWaveFile(@"C:\Users\guill\Videos\reunion.wav");

                recognizer.LoadGrammar(new DictationGrammar()); // Dictation = tout ce qui est dit

                recognizer.SpeechRecognized += (s, e) =>
                {
                    foreach (var result in e.Result.Alternates)
                    {
                        Console.WriteLine("Texte reconnu : " + result.Text);
                        LoggerService.LogDebug("Texte reconnu : " + result.Text);
                    }
                };

                Console.WriteLine("Transcription en cours...");
                LoggerService.LogDebug("Transcription en cours");
                recognizer.Recognize(); // Synchrone, bloque jusqu’à la fin du fichier
            }

        }

        private void BtnStopParler_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BtnParler.IsEnabled = true;
                BtnStopParler.IsEnabled = false;
                Speech.Stop();
                LoggerService.LogDebug("Speech.DictationResult : " + Speech.DictationResult);

                Speech.Lire(Speech.DictationResult);


            }
            catch(Exception ex) 
            {
                LoggerService.LogError($"BtnStopParler_Click : {ex.Message}");
            }
        }
        #endregion

    }


    public class MainViewModel : BaseViewModel
    {
        public SnackbarMessageQueue SnackbarQueue { get; } = new SnackbarMessageQueue(TimeSpan.FromSeconds(3));

        public ICommand RefreshCommand { get; }
        public ICommand QuitCommand { get; }
        public ICommand ParlerCommand { get; }
        public ICommand StopParlerCommand { get; }

        public MainViewModel()
        {
            RefreshCommand = new RelayCommand(_ => ShowSnackbar("Services vérifiés !"));
            QuitCommand = new RelayCommand(_ => Application.Current.Shutdown());
            ParlerCommand = new RelayCommand(_ => ShowSnackbar("Assistant vocal activé"));
            StopParlerCommand = new RelayCommand(_ => ShowSnackbar("Assistant vocal désactivé"));
        }

        private void ShowSnackbar(string message)
        {
            SnackbarQueue.Enqueue(message);
        }



    }
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object, bool> _canExecute;

        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter) => _canExecute?.Invoke(parameter) ?? true;
        public void Execute(object parameter) => _execute(parameter);
        public event EventHandler CanExecuteChanged;
    }

}