#!/usr/bin/env node
/**
 * Quick probe: does the Loxia backend pass `tool_calls` through on the
 * non-streaming `/llm/chat` endpoint? We need to know before building
 * the OPERATING POSTURE harness.
 */
import { readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';

const BASE_URL = process.env.LOXIA_BASE_URL ||
  'https://loxia-api-g7hrb8bxdae8a2h7.z02.azurefd.net';

function loadKey() {
  if (process.env.LOXIA_API_KEY) return process.env.LOXIA_API_KEY;
  try {
    const p = join(homedir(), '.loxia', 'keys.json');
    const j = JSON.parse(readFileSync(p, 'utf8'));
    return j?.backend?.key || null;
  } catch { return null; }
}

const apiKey = loadKey();
if (!apiKey) {
  console.error('No Loxia API key found.');
  process.exit(1);
}

const model = process.argv[2] || 'gpt-4.1-nano';

const tools = [{
  type: 'function',
  function: {
    name: 'memory',
    description: 'Persistent memory store for the agent. Use to list/read/add/append memories.',
    parameters: {
      type: 'object',
      properties: {
        action: { type: 'string', enum: ['list', 'read', 'add', 'append'] },
        id: { type: 'string' },
        title: { type: 'string' },
        content: { type: 'string' },
      },
      required: ['action'],
    },
  },
}];

const systemPrompt =
  'You are an agent. You can call the `memory` tool to list/read/add/append memories. ' +
  'When asked to remember something, use memory.add. Be concise.';

const userMessage =
  'Please remember this for later: the API base URL is https://example.com/v1, and we should always use bearer tokens.';

const payload = {
  conversationId: 'probe-1',
  message: userMessage,
  messages: [{ role: 'user', content: userMessage }],
  model,
  requestId: 'probe-1',
  options: { max_tokens: 500, temperature: 0.2, tools },
  platformProvided: true,
  systemPrompt,
  apiKey,
};

console.log(`POST ${BASE_URL}/llm/chat   model=${model}`);
const res = await fetch(`${BASE_URL}/llm/chat`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${apiKey}`,
    'X-Request-ID': 'probe-1',
  },
  body: JSON.stringify(payload),
});

console.log('HTTP', res.status, res.statusText);
const text = await res.text();
try {
  const j = JSON.parse(text);
  console.log('JSON keys:', Object.keys(j));
  console.log(JSON.stringify(j, null, 2).slice(0, 4000));
} catch {
  console.log('RAW:', text.slice(0, 4000));
}
