import { createLogger } from "../logger.js";
import { isLlmConfigured, runLlmText } from "../integrations/cloud/llm/run.js";
const log = createLogger("research");
const DEFAULT_MAX_SOURCES = 8;
const DEFAULT_MAX_CHARS_PER_SOURCE = 4e3;
const DEFAULT_TIMEOUT_MS = 6e4;
const DEFAULT_MAX_TOKENS = 3e3;
async function synthesizeLocal(question, sources, opts = {}) {
  if (!isLlmConfigured()) {
    throw new Error("LLM not configured. Set WIGOLO_LLM_PROVIDER or a provider API key.");
  }
  const maxSources = opts.maxSources ?? DEFAULT_MAX_SOURCES;
  const maxCharsPerSource = opts.maxCharsPerSource ?? DEFAULT_MAX_CHARS_PER_SOURCE;
  const sliced = sources.slice(0, maxSources);
  const sourceBlocks = sliced.map((s, i) => {
    const body = s.markdown.length > maxCharsPerSource ? s.markdown.slice(0, maxCharsPerSource) : s.markdown;
    return `[${i + 1}] ${s.title}
${body}`;
  });
  const prompt = `You answer questions using ONLY the provided sources. Cite each fact with [N] where N is the source number.

Question: ${question}

Sources:
${sourceBlocks.join("\n\n")}`;
  try {
    const result = await runLlmText({
      prompt,
      maxTokens: opts.maxTokens ?? DEFAULT_MAX_TOKENS,
      modelOverride: opts.modelOverride,
      timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
    });
    log.info("local synthesis ok", { provider: result.provider, model: result.model, latencyMs: result.latencyMs });
    return { text: result.text, citations: extractCitations(result.text) };
  } catch (err) {
    log.error("local synthesis request failed", { error: err instanceof Error ? err.message : String(err) });
    throw err;
  }
}
function isLocalLlmEnabled() {
  return isLlmConfigured();
}
function extractCitations(text) {
  const matches = text.match(/\[(\d+)\]/g);
  if (!matches) return [];
  const seen = /* @__PURE__ */ new Set();
  const out = [];
  for (const m of matches) {
    const n = Number(m.slice(1, -1));
    if (!Number.isFinite(n) || n < 1) continue;
    const idx = n - 1;
    if (seen.has(idx)) continue;
    seen.add(idx);
    out.push(idx);
  }
  return out;
}
export {
  isLocalLlmEnabled,
  synthesizeLocal
};
//# sourceMappingURL=synthesis-local.js.map