using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MercatorApi;
using MercatorUi;
using MercatorExtensions;

namespace MyAssembly
{
    public static  class ChatGPT
    {
        public static void CheckSuppliers()
        {
            MercatorAI.FactoryOpenAI factory = new MercatorAI.FactoryOpenAI();
            MercatorAI.Interfaces.IOpenAiChat openAiChat = factory.CreateOpenAiChat("gpt -4o", out string error);
            if (!string.IsNullOrEmpty(error))
            {
                Dialogs.Stop("Impossible d'initialiser le chat d'OpenAI : " + error);
                return;
            }

            string reqSql = @"select fou.f_id as idfournisseur,lignes_c.journal,lignes_c.piece,(case when lignes_c.tot<0 then -lignes_c.tot else 0 end) as debit,(case when lignes_c.tot>0 then lignes_c.tot else 0 end) as credit,lignes_c.date,case when echeance> '19000101' then lignes_c.echeance else null end as echeance,lignes_c.commentair as info
                                    from LIGNES_C
                                    inner join FOU on lignes_c.id_fou=fou.f_id
                                    where (lignes_c.lettrage <= 0) and (lignes_c.type_ligne >= 0)
                                    order by fou.f_id,lignes_c.date".UnIndent(9);

            MercatorUi.Wait.WaitStatic.WaitWindow(Api.Iif_langue(Globals.Langue, IifLangueEnum.SeekingData));
            List<BookingDescriptor> bookings = Api.Zselect<BookingDescriptor>(Globals.RepData, reqSql);
            if (bookings == null)
            {
                MercatorUi.Wait.WaitStatic.WaitClear();
                return;
            }

            string question = @"Indique-moi les anomalies potentielles comme :
                                - mouvements non lettrés qui pourraient l'être (montants identiques ou semblables, solde de plusieurs mouvements à zéro ou proche de zéro, ...),
                                - paiements sans facture,
                                - factures sans règlement mais en ignorant celles qui ne sont pas encore échues,
                                - d'autres anomalies que tu détecterais.
                                Les paiements sont dans les journaux ING et VBDA. ODV est un journal d'opérations diverses de correction.".UnIndent(8);

            string systemMessage = "Tu es un assistant comptable expert. Tu réponds EXCLUSIVEMENT en Markdown. Voici une liste de postes ouverts comptables fournisseurs en date de ce jour au format JSON.\n" + Api.JsonConvertSerializeObject(bookings);

            MercatorAI.FactoryOpenAI.ChatOptions chatOptions = new MercatorAI.FactoryOpenAI.ChatOptions
            {
                Temperature = 0.2f, // autoriser une légère variation
                TopP = 1.0f
            };

            MercatorUi.Forms.Other.ChatForm.SimpleOpenAiChat("gpt-4o", "Analyse postes ouverts fournisseurs", systemMessage, question, autoAskFirstQuestion: false, chatOptions: chatOptions, userControl: null, responseUpdater: null, standardStreamingAction: MercatorUi.Forms.Other.ChatForm.StandardStreamingActionEnum.RawStreamShow);
        }

        public class BookingDescriptor
        {
            public string IdFournisseur { get; set; }
            public string Journal { get; set; }
            public Int64 Piece { get; set; }
            public decimal Debit { get; set; }
            public decimal Credit { get; set; }
            public DateTime Date { get; set; }
            public DateTime? Echeance { get; set; }
            public string Info { get; set; }
        }
    }
}