{********************************************************************}
{                                                                    }
{ written by TMS Software                                            }
{            copyright (c) 2025                                      }
{            Email : info@tmssoftware.com                            }
{            Web : http://www.tmssoftware.com                        }
{                                                                    }
{ The source code is given as is. The author is not responsible      }
{ for any possible damage done due to the use of this code.          }
{ The complete source code remains property of the author and may    }
{ not be distributed, published, given or sold in any form as such.  }
{ No parts of the source code can be included in any other component }
{ or application without written authorization of the author.        }
{********************************************************************}

unit Uairag;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  System.IOUtils, Vcl.Controls, Vcl.Forms, Vcl.Graphics, Vcl.Dialogs,
  Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Imaging.pngimage,
  PDFExtract, TMS.MCP.CustomComponent,
  TMS.MCP.CloudBase, TMS.MCP.CloudAI;

type
  TForm1 = class(TForm)
    OpenBtn: TButton;
    OpenDialog1: TOpenDialog;
    ProcBtn: TButton;
    ServicesCmb: TComboBox;
    ProgressBar1: TProgressBar;
    Timer1: TTimer;
    contextmemo: TMemo;
    promptmemo: TMemo;
    Label1: TLabel;
    Label2: TLabel;
    resultmemo: TMemo;
    KeysBtn: TButton;
    TMSMCPCloudAI1: TTMSMCPCloudAI;
    procedure OpenBtnClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure ProcBtnClick(Sender: TObject);
    procedure ServicesCmbChange(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure KeysBtnClick(Sender: TObject);
    procedure TMSMCPCloudAI1Executed(Sender: TObject;
      AResponse: TTMSMCPCloudAIResponse; AHttpStatusCode: Integer;
      AHttpResult: string);
  private
    { Private declarations }
  public
    { Public declarations }
    fname1: string;
    fname2: string;
  end;

var
  Form1: TForm1;

implementation

uses
  Uaikeys;

{$R *.dfm}

procedure TForm1.OpenBtnClick(Sender: TObject);
var
  ext,s: string;
begin
  if opendialog1.Execute then
  begin
    fname1 := opendialog1.FileName;

    ext := ExtractFileExt(fname1);

    if uppercase(ext) = '.TXT' then
    begin
      contextmemo.Lines.LoadFromFile(fname1);

      if pos('SNOW WHITE', uppercase(fname1)) > 0 then
      begin
        promptmemo.Lines.Text := 'Who are the main characters in the story of Snow White and how many dwarfs are there?';
      end;

    end
    else
    if uppercase(ext) = '.PDF' then
    begin
      if pos('EURO AREA', uppercase(fname1)) > 0 then
      begin
        promptmemo.Lines.Text := 'Summarize in one paragraph your findings on the state of the European economy and the buying power of its citizens based on the accompanying report';
      end;

      // extract plain text from the PDF
      s := ExtractPdfText(fname1);
      contextmemo.Lines.Text := s;
      fname1 := TPath.GetTempFileName;
      TFile.WriteAllText(fname1, s);
    end
    else
      ShowMessage('Need a TXT or PDF file for RAG');
  end;
end;

procedure TForm1.KeysBtnClick(Sender: TObject);
var
  AIKeysForm: TAIKeysForm;
begin
  AIKeysForm := TAIKeysForm.Create(nil);
  try
    AIKeysForm.ShowModal;
    // reload API keys
    TMSMCPCloudAI1.APIKeys.LoadFromFile(keysfile,keyspwd);
  finally
    AIKeysForm.Free;
  end;
end;

procedure TForm1.ProcBtnClick(Sender: TObject);
begin
  if (fname1 <> '') and FileExists(fname1) then
  begin
    resultmemo.Lines.Clear;
    timer1.Enabled := true;
    ProcBtn.Enabled := false;
    TMSMCPCloudAI1.AddFile(fname1, aiftText);
    TMSMCPCloudAI1.Context.Clear;
    TMSMCPCloudAI1.Context.Text := promptmemo.Lines.Text;
    try
      TMSMCPCloudAI1.Execute;
    except
      on E: Exception do
      begin
        timer1.Enabled := false;
        ProcBtn.Enabled := true;
        ProgressBar1.Position := 0;
        ShowMessage(e.Message);
      end;
    end;
  end
  else
    ShowMessage('No text content file was selected');
end;

procedure TForm1.ServicesCmbChange(Sender: TObject);
var
  i: integer;
begin
  if ServicesCmb.ItemIndex = -1 then
    Exit;

  i := integer(ServicesCmb.Items.Objects[ServicesCmb.ItemIndex]);
  TMSMCPCloudAI1.Service := TTMSMCPCloudAIService(i);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  TMSMCPCloudAI1.Logging := true;
  TMSMCPCloudAI1.LogFileName := '.\airag.log';

  TMSMCPCloudAI1.APIKeys.LoadFromFile(keysfile,keyspwd);

  ServicesCmb.ItemIndex := -1;
  ServicesCmb.Items.Assign(TMSMCPCLoudAI1.GetServices(true));
  ServicesCmb.ItemIndex := 0;
  ServicesCmbChange(ServicesCmb);
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  if ProgressBar1.Position = 100 then
    ProgressBar1.Position := 0
  else
    ProgressBar1.Position := ProgressBar1.Position + 1;
end;

procedure TForm1.TMSMCPCloudAI1Executed(Sender: TObject;
  AResponse: TTMSMCPCloudAIResponse; AHttpStatusCode: Integer;
  AHttpResult: string);
begin
  resultmemo.Lines.Clear;

  timer1.Enabled := false;
  ProcBtn.Enabled := true;

  ProgressBar1.Position := 0;
  if AHttpStatusCode = 200 then
    resultmemo.Lines.Text := AResponse.Content.Text
  else
  begin
    resultmemo.Lines.Text := AHttpResult;
    ShowMessage('Error processing request:'+ AHttpStatusCode.ToString);
  end;

end;

end.
