REM --- NeReLa Basic OpenAI Chat Client with JSON Parsing ---
REM This program uses the HTTP.POST$ function to send a prompt
REM to the OpenAI Chat Completions API and then parses the
REM JSON response to extract the message content.

CLS
PRINT "--- OpenAI API Chat Client (with History) for jdBasic ---"
PRINT

API_KEY$ = Getenv$("OPENAI_API_KEY")

IF LEN(API_KEY$) = 0 THEN
    PRINT "Error: OPENAI_API_KEY environment variable not set."
    GOTO ENDE
ENDIF

REM The API endpoint for chat completions
API_URL$ = "https://api.openai.com/v1/chat/completions"

REM Set the required HTTP headers for the OpenAI API
HTTP.SETHEADER "Authorization", "Bearer " + API_KEY$
'HTTP.SETHEADER "Content-Type", "application/json"

PRINT
PRINT "Headers are set. You can now start chatting."
PRINT "Type 'exit' or 'quit' to end the program."
PRINT

' --- Initialize an array to hold the entire conversation history ---
conversation_history = []
DIM payload AS MAP ' This can stay outside the loop as it's fully redefined each time

DO
    PRINT
    INPUT "> "; USER_PROMPT$

    IF LCASE$(USER_PROMPT$) = "exit" OR LCASE$(USER_PROMPT$) = "quit" THEN
       GOTO ENDE
    ENDIF

    PRINT "Sending to OpenAI..."
    
    ' This creates a fresh map for each turn, preventing history from being overwritten.
    DIM user_message AS MAP
    DIM assistant_message AS MAP

    ' --- Add the user's new message to the history ---
    user_message{"role"} = "user"
    user_message{"content"} = USER_PROMPT$
    conversation_history = APPEND(conversation_history, user_message)

    ' --- Create the payload using the FULL conversation history ---
    payload{"model"} = "gpt-4o-mini"
    payload{"messages"} = conversation_history

    TRY
        JSON_BODY$ = JSON.STRINGIFY$(payload)
        RESPONSE$ = HTTP.POST$(API_URL$, JSON_BODY$, "application/json")
        RESPONSE_JSON = JSON.PARSE$(RESPONSE$)
    CATCH
        PRINT "Error in JSON.PARSE$(RESPONSE$)"
        PRINT "Error Code: "; ERR
        PRINT "Error Line: "; ERL
        PRINT "Error Message: "; ERRMSG$
    ENDTRY

    'print RESPONSE_JSON 
    AI_MESSAGE$ = RESPONSE_JSON{"choices"}[0]{"message"}{"content"}
    
    PRINT
    PRINT "AI: "; AI_MESSAGE$

    ' --- Add the AI's response to the history for the next turn ---
    assistant_message{"role"} = "assistant"
    assistant_message{"content"} = AI_MESSAGE$
    conversation_history = APPEND(conversation_history, assistant_message)

LOOP UNTIL 1=2


ENDE:
Print "Bye."