import { readFile } from 'node:fs/promises';
import { choice, TypeSafeClient } from '@typesafe-ai/sdk';

// Run one selected sample. There are no retries or automatic batch requests.
const [file, sampleId] = process.argv.slice(2);
if (!file || !sampleId || !process.env.TYPESAFE_API_KEY) {
  throw new Error('Set TYPESAFE_API_KEY, then run: node run-choice-sample.mjs FIXTURE.json SAMPLE_ID');
}
const raw = await readFile(file, 'utf8');
if (Buffer.byteLength(raw) > 1_000_000) throw new Error('Fixture is too large');
/** @type {{samples: Array<{id: string, request: {context: string, question: string, choices: string[]}}>}} */
const fixture = JSON.parse(raw);
const matches = fixture.samples.filter(sample => sample.id === sampleId);
if (matches.length !== 1) throw new Error('Select exactly one existing sample ID');
const { context, question, choices } = matches[0].request;
if (typeof context !== 'string' || typeof question !== 'string' || context.length > 12000
  || question.length > 500 || !Array.isArray(choices) || choices.length < 2 || choices.length > 12
  || choices.some(label => typeof label !== 'string' || !label || label.length > 120)
  || new Set(choices).size !== choices.length) throw new Error('Invalid sample request');
const client = new TypeSafeClient({ logLevel: 'off' });
const start = performance.now();
try {
  const result = await client.systemOne({ model: 'jev-latest', state: { context, question, choices },
    questions: { decision: choice(question, Object.fromEntries(choices.map(label => [label, null]))) } },
    { timeout: 10000, retry: { maxRetries: 0 } });
  console.log(JSON.stringify({ sampleId, elapsedMs: Math.round(performance.now() - start), result }, null, 2));
} catch {
  console.error('The API request failed. No retry was sent; check your account and network privately.');
  process.exitCode = 1;
}
