unit uGemini;
{
This code is part of the TiCodEd Application, designed to develop for the
TI-99/4a Homecomputer in a modern, structured way.

BSD License
Copyright (c) 2026, Stefan Bauch, TiCodEd <at> lizardware <dot> de

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

}

{$mode ObjFPC}{$H+}

interface

uses
  Classes, SysUtils,  fphttpclient, fpjson, jsonparser, opensslsockets;

function  AskGemini(UserPrompt,ContextFiles,Thread,Answer: TStrings):integer;
procedure SetupGemini(APIKey,URL,Model: String);
procedure CloseGemini;


implementation

uses dialogs;

type
    EGeminiAPIError = class(Exception);

var
    FApiKey: string;
    FBaseURL:string;
    FModel:  string;
    FHttpClient: TFPHTTPClient;
    err : string;



function BuildRequestBody(const aPrompt: string): TJSONObject;
var
  LPart: TJSONObject;
  LPartsArray: TJSONArray;
  LContent: TJSONObject;
  LContentsArray: TJSONArray;
begin
  Result := TJSONObject.Create;
  LContentsArray := TJSONArray.Create;
  Result.Add('contents', LContentsArray);
  LContent := TJSONObject.Create;
  LContentsArray.Add(LContent);
  LPartsArray := TJSONArray.Create;
  LContent.Add('parts', LPartsArray);
  LPart := TJSONObject.Create;
  LPart.Add('text', aPrompt);
  LPartsArray.Add(LPart);
end;


function ParseResponse(const aJSONResponse: string): string;
var
  LJSONData, LTextNode, LErrorNode: TJSONData;
begin
  Result := '';
  if Trim(aJSONResponse) = '' then
    raise EGeminiAPIError.Create('API returned empty response.');
  try
    LJSONData := GetJSON(aJSONResponse);
    try
      LTextNode := LJSONData.FindPath('candidates[0].content.parts[0].text');
      if Assigned(LTextNode) then
      begin
        Result := LTextNode.AsString;
      end
      else
      begin
        LErrorNode := LJSONData.FindPath('error.message');
        if Assigned(LErrorNode) then
          raise EGeminiAPIError.CreateFmt('API Error: %s', [LErrorNode.AsString])
        else
          raise EGeminiAPIError.Create('No valid content in API-response.');
      end;
    finally
      LJSONData.Free;
    end;
  except
    on E: Exception do
    begin
      err := E.Message;
      if E is EGeminiAPIError then raise
      else raise EGeminiAPIError.Create('Error when parsing JSON-reply: ' + E.Message);
    end;
  end;
end;

procedure GenerateContent(const aPrompt: TStrings; aResult: TStrings);
var
  LURL: string;
  LRequestBody: TJSONObject;
  LRequestStream: TStringStream;
  LResponseContent, PromptText: string;
begin
  err := '';
  if not Assigned(aPrompt) or not Assigned(aResult) then
    raise EGeminiAPIError.Create('Prompt- and Result-TStrings must be assigned.');

  aResult.Clear;

  // convert TStrings to String for smaller prompts up to ~100KB)
  PromptText := aPrompt.Text;

  LURL := Format('%s%s:generateContent?key=%s', [FBaseURL, FModel, FApiKey]);

  LRequestBody := BuildRequestBody(PromptText);
  LRequestStream := TStringStream.Create(LRequestBody.AsJSON, TEncoding.UTF8);
  LRequestBody.Free;
  LRequestStream.Position := 0;
  try
    try
      FHttpClient.RequestHeaders.Clear;
      FHttpClient.RequestHeaders.Add('Content-Type: application/json');
      FHttpClient.RequestBody := LRequestStream;
      LResponseContent := FHttpClient.Post(LURL);

      aResult.Text := ParseResponse(LResponseContent);
    except
      on E: EHTTPClient do
        raise EGeminiAPIError.Create('HTTP-Error: ' + E.Message);
      on E: Exception do
        raise EGeminiAPIError.Create('A Network- or Systemerror occurred: ' + E.Message);
    end;
  finally
    LRequestStream.Free;
    FHttpClient.RequestBody := nil;
  end;
end;

procedure SetupGemini(APIKey,URL,Model: String);
begin
    FApiKey :=APIKey;
    FBaseURL:=URL;
    FModel  :=Model;
    if (pos('PREVIEW',uppercase(model))>0) or
       (pos('GEMMA',uppercase(model))>0) or
       (pos('-001',model)>0)
       then FBaseURL := StringReplace(FBaseURL,'/v1/','/v1beta/',[]);
    FHttpClient := TFPHTTPClient.Create(nil);
    FHttpClient.AllowRedirect := True; // Redirects allowed
end;

procedure CloseGemini;
begin
   FHttpClient.Free;
end;

function AskGemini(UserPrompt,ContextFiles,Thread,Answer: TStrings):integer;
var context,prompt: TStringList;
    s : string;
begin
  result  := 0;
  // ShowMessage(ContextFiles.CommaText);
  prompt  := TStringList.Create;
  context := TStringList.Create;
  for s in ContextFiles do if FileExists('./lib/ai/'+s) then begin
     context.LoadFromFile('./lib/ai/'+s);
     prompt.AddStrings(context);
  end;
  // Add history etc
  prompt.AddStrings(Thread);

  prompt.Add('');
  prompt.Add('=== end of context ===');
  prompt.Add('');
  if Answer.Count>0 then begin
    prompt.Add('<CODE>');
    prompt.AddStrings(Answer);
    prompt.Add('</CODE>');
    prompt.Add('');
  end;
  Answer.Clear;
  Answer.Add('Contacting GEMINI...');
  prompt.Add('<PROMPT>');
  prompt.AddStrings(UserPrompt);
  prompt.Add('</PROMPT>');
  prompt.SaveToFile('./lib/ai/LatestPrompt.txt');

  try
    GenerateContent(prompt, Answer);
  finally
    Answer.Add(Err);
    result := -1;
  end;
end;


end.

