import { logger } from '../../logger.js';
import type { ReflectionResult } from './types.js';
import { REFLECTION_TOOL_SCHEMA } from './reflection-schema.js';

export interface ReflectionLlmConfig {
  endpoint: string;
  model: string | undefined;
  apiKey?: string;
}

export interface ReflectionLlmResult {
  parsed: ReflectionResult;
  tokensIn: number;
  tokensOut: number;
  durationMs: number;
  raw: unknown;
}

export async function callReflectionLlm(
  cfg: ReflectionLlmConfig,
  systemPrompt: string,
  userPrompt: string
): Promise<ReflectionLlmResult> {
  const start = Date.now();
  const body: Record<string, unknown> = {
    messages: [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: userPrompt },
    ],
    tools: [REFLECTION_TOOL_SCHEMA],
    tool_choice: { type: 'function', function: { name: 'submit_reflection' } },
    temperature: 0.2,
  };
  if (cfg.model) {
    body['model'] = cfg.model;
  }
  const resp = await fetch(`${cfg.endpoint}/chat/completions`, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      ...(cfg.apiKey ? { authorization: `Bearer ${cfg.apiKey}` } : {}),
    },
    body: JSON.stringify(body),
  });
  if (!resp.ok) {
    throw new Error(`reflection LLM HTTP ${resp.status}: ${await resp.text()}`);
  }
  const data = await resp.json() as any;
  const toolCall = data.choices?.[0]?.message?.tool_calls?.[0];
  if (!toolCall) throw new Error('reflection LLM returned no tool_call');
  const parsed = JSON.parse(toolCall.function.arguments) as ReflectionResult;
  return {
    parsed,
    tokensIn: data.usage?.prompt_tokens ?? 0,
    tokensOut: data.usage?.completion_tokens ?? 0,
    durationMs: Date.now() - start,
    raw: data,
  };
}
