local createTrapGpt = require('/apis/libtrapgpt');
local createVersion = require('/apis/libversion');

local args = table.pack(...);

local function printUsage()
  print('trapgpt usage:');
  print();
  print('  trapgpt');
  print('  trapgpt --version');
  print('  trapgpt --help');
  print();
  print('settings required:');
  print('  opencc.server_url');
  print();
  print('settings optional:');
  print('  trapgpt.throttle_seconds (default: 5)');
  print('  trapgpt.max_reply_chars  (default: 160)');
  print('  trapgpt.prefix           (default: TrapGPT)');
end

local command = args[1];

if command == '--version' or command == '-version' or command == 'version' then
  print('v' .. createVersion().forSelf());
  return;
end

if command == '--help' or command == '-help' or command == 'help' then
  printUsage();
  return;
end

if args.n > 0 then
  printUsage();
  return;
end

local chatBox = peripheral.find('chat_box') or peripheral.find('chatBox');
if not chatBox then
  error('chat_box peripheral not found');
end

local trapgpt = createTrapGpt({ chatBox = chatBox });

local function listenChat()
  while true do
    local _, username, message, uuid, isHidden, messageUtf8 = os.pullEvent('chat');
    trapgpt.onChat(username, message, uuid, isHidden, messageUtf8);
  end
end

print('trapgpt listening');
parallel.waitForAny(listenChat, function() trapgpt.run(); end);
