import { loadConfig, type Config } from '../config.js';
import { resolveModelEndpoint } from './inference/provider.js';

const TIMEOUT_MS = 10_000;

export async function taskModelCompletion(opts: {
  system: string;
  user: string;
  maxTokens?: number;
  temperature?: number;
  fallbackModel?: string;
}): Promise<string> {
  const config = loadConfig();
  const maxTokens = opts.maxTokens ?? 30;
  const temperature = opts.temperature ?? 0.3;

  // v2.x (W3): resolve the endpoint through the shared provider-aware
  // resolver instead of a local LLAMA_SWAP_URL fallback. This ensures
  // composite model ids (e.g. "sam-desktop/qwen3.6-35b") route to the
  // correct provider, and bare ids resolve through the default provider.
  const model = config.FAST_MODEL ?? opts.fallbackModel ?? config.DEFAULT_MODEL;
  const { url, model: resolvedModel, headers } = resolveModelEndpoint(config, model);

  try {
    const res = await fetch(`${url}/v1/chat/completions`, {
      method: 'POST',
      headers: { ...headers, 'X-Boo-Source': 'boochat' },
      body: JSON.stringify({
        model: resolvedModel,
        messages: [
          { role: 'system', content: opts.system },
          { role: 'user', content: opts.user },
        ],
        max_tokens: maxTokens,
        temperature,
        stream: false,
        chat_template_kwargs: { enable_thinking: false },
      }),
      signal: AbortSignal.timeout(TIMEOUT_MS),
    });
    if (!res.ok) {
      const text = await res.text().catch(() => '');
      console.warn(`task-model: ${res.status} ${text.slice(0, 200)}`);
      return '';
    }
    const data = (await res.json()) as {
      choices?: Array<{
        message?: { content?: string; reasoning_content?: string };
      }>;
    };
    const choice = data.choices?.[0]?.message;
    if (!choice) return '';
    const content = (choice.content ?? '').trim();
    if (content.length > 0) return content;
    const reasoning = choice.reasoning_content ?? '';
    if (reasoning.length === 0) return '';
    const lines = reasoning.split('\n').map((l) => l.trim()).filter((l) => l.length > 0);
    return lines[lines.length - 1] ?? '';
  } catch (err) {
    console.warn('task-model: request failed', err);
    return '';
  }
}
