#!/usr/bin/env elixir
# PUBLIC DOMAIN - NO LICENSE, NO WARRANTY
# Copyright 2025 TimeHexOn & foxhop & russell@unturf
# https://www.permacomputer.com


# Load dependencies (skip Mix.install when running via Docker with pre-compiled deps)
unless System.get_env("MIX_ENV") == "prod" do
  Mix.install([
    {:httpoison, "~> 2.2"},
    {:jason, "~> 1.4"}
  ])
end

# Load the module
Code.require_file("lib/uncloseai.ex", __DIR__)

# Demo program showing library usage
alias UncloseAI.Client

IO.puts("=== UncloseAI Elixir Client (with Streaming) ===\n")

# Initialize client
client = Client.new()

if Enum.empty?(client.models) do
  IO.puts("ERROR: No models discovered")
  System.halt(1)
end

# Non-streaming chat example
IO.puts("=== Non-Streaming Chat ===")
IO.puts("Model: #{Enum.at(client.models, 0).id}")

messages = [%{role: "user", content: "Explain quantum computing in one sentence"}]

case Client.chat(client, messages) do
  {:ok, response} -> IO.puts("Response: #{response}\n")
  {:error, reason} -> IO.puts("Error: #{inspect(reason)}\n")
end

# Streaming chat example
model_idx = if length(client.models) >= 2, do: 1, else: 0
IO.puts("=== Streaming Chat ===")
IO.puts("Model: #{Enum.at(client.models, model_idx).id}")
IO.write("Response: ")

messages = [%{role: "user", content: "Write a hello world program in Elixir"}]

client
|> Client.chat_stream(messages, model_idx: model_idx)
|> Enum.each(&IO.write/1)

IO.puts("\n")

# TTS example
if !Enum.empty?(client.tts_endpoints) do
  IO.puts("=== TTS Speech Generation ===")
  IO.puts("Model: tts-1")

  case Client.tts(client, "Hello from UncloseAI Elixir client!",
         output_file: "/tmp/speech.mp3") do
    {:ok, file} -> IO.puts("Audio saved to #{file}")
    {:error, reason} -> IO.puts("TTS failed: #{inspect(reason)}")
  end
end

IO.puts("\n=== Examples Complete ===")
