      *> PUBLIC DOMAIN - NO LICENSE, NO WARRANTY
      *> Copyright 2025 TimeHexOn & foxhop & russell@unturf
      *> https://www.permacomputer.com

       IDENTIFICATION DIVISION.
       PROGRAM-ID. UNCLOSEAI.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 MESSAGE-TEXT PIC X(200).
       01 MODEL-INDEX PIC 9.
       01 TTS-TEXT PIC X(200).
       01 TTS-VOICE PIC X(20).
       01 TEMP-CMD PIC X(500).

       PROCEDURE DIVISION.

       UNCLOSEAI-INIT.
           DISPLAY "Initializing UncloseAI client...".
           CALL "SYSTEM" USING
               "for i in {1..9999}; do ep=$MODEL_ENDPOINT_$i; "
               "[ -z $ep ] && break; echo Endpoint $i: $ep; done".

       UNCLOSEAI-CHAT.
           DISPLAY "Model: first available".
           STRING "ep=$MODEL_ENDPOINT_1; "
                  "curl -s $ep/chat/completions "
                  "-H Content-Type:application/json "
                  "-d {model:qwen,messages:[{role:user,content:"
                  MESSAGE-TEXT "}],stream:false}"
                  DELIMITED BY SIZE
                  INTO TEMP-CMD
           END-STRING
           CALL "SYSTEM" USING TEMP-CMD.

       UNCLOSEAI-CHAT-STREAM.
           DISPLAY "Model: streaming".
           STRING "ep=$MODEL_ENDPOINT_1; "
                  "curl -s --no-buffer $ep/chat/completions "
                  "-H Content-Type:application/json "
                  "-d {model:qwen,messages:[{role:user,content:"
                  MESSAGE-TEXT "}],stream:true}"
                  DELIMITED BY SIZE
                  INTO TEMP-CMD
           END-STRING
           CALL "SYSTEM" USING TEMP-CMD.

       UNCLOSEAI-TTS.
           DISPLAY "Generating speech...".
           STRING "curl -s $TTS_ENDPOINT_1/audio/speech "
                  "-H Content-Type:application/json "
                  "-d {model:tts-1,input:"
                  TTS-TEXT ",voice:" TTS-VOICE "} "
                  "-o /tmp/speech.mp3"
                  DELIMITED BY SIZE
                  INTO TEMP-CMD
           END-STRING
           CALL "SYSTEM" USING TEMP-CMD
           DISPLAY "Audio saved to /tmp/speech.mp3".

       DEMO-MAIN.
           DISPLAY "=== UncloseAI COBOL Client ===".
           DISPLAY " ".

           PERFORM UNCLOSEAI-INIT.
           DISPLAY " ".

           DISPLAY "=== Non-Streaming Chat ===".
           MOVE "Explain quantum computing" TO MESSAGE-TEXT.
           MOVE 0 TO MODEL-INDEX.
           PERFORM UNCLOSEAI-CHAT.
           DISPLAY " ".

           DISPLAY "=== Streaming Chat ===".
           MOVE "Write hello world in COBOL" TO MESSAGE-TEXT.
           MOVE 1 TO MODEL-INDEX.
           PERFORM UNCLOSEAI-CHAT-STREAM.
           DISPLAY " ".

           DISPLAY "=== TTS Speech Generation ===".
           MOVE "Hello from COBOL" TO TTS-TEXT.
           MOVE "alloy" TO TTS-VOICE.
           PERFORM UNCLOSEAI-TTS.
           DISPLAY " ".

           DISPLAY "=== Examples Complete ===".
           STOP RUN.
