import { readFile, writeFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';

export async function requestDraft(input, { key, model, fetchImpl = fetch }) {
  if (!key || !model) throw new Error('Set DIGITALOCEAN_TOKEN and DIGITALOCEAN_MODEL in .env.');
  if (!input || typeof input.instruction !== 'string' || !input.instruction.trim() || input.facts === undefined) {
    throw new Error('Input needs an instruction string and facts.');
  }
  const response = await fetchImpl('https://inference.do-ai.run/v1/chat/completions', {
    method: 'POST',
    headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ model, max_tokens: 1200, messages: [
      { role: 'system', content: input.instruction },
      { role: 'user', content: JSON.stringify(input.facts) },
    ] }),
    signal: AbortSignal.timeout(60000),
  });
  if (!response.ok) throw new Error(`Inference failed (HTTP ${response.status}); no draft accepted.`);
  const data = await response.json();
  const draft = data.choices?.[0]?.message?.content;
  if (data.choices?.[0]?.finish_reason !== 'stop' || typeof draft !== 'string' || !draft.trim()) {
    throw new Error('Missing or incomplete response; no draft accepted.');
  }
  return { status: 'needs-human-review', model, draft };
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  try {
    const [, , inputFile, outputFile] = process.argv;
    if (!inputFile || !outputFile || inputFile === outputFile) throw new Error('Usage: node --env-file=.env request.mjs input.json new-result.json');
    const input = JSON.parse(await readFile(inputFile, 'utf8'));
    const result = await requestDraft(input, { key: process.env.DIGITALOCEAN_TOKEN, model: process.env.DIGITALOCEAN_MODEL });
    await writeFile(outputFile, JSON.stringify(result, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
    console.log(`Saved ${outputFile}. Compare every claim with ${inputFile} before using it.`);
  } catch (error) {
    console.error(error.message);
    process.exitCode = 1;
  }
}
