// prompt-engine.jsx — browser side of optimization.
// Model/mode definitions and meta-prompt building live in engine-core.js (shared
// with the server). This file just calls the backend so the API key stays server-side.
//
// Backend resolution order:
//   1) window.claude.complete  — Anthropic preview/artifact environment (no key needed).
//   2) POST /api/optimize      — the Vercel serverless proxy that holds GEMINI_API_KEY.

async function callProxy(rawPrompt, modelId, modeId) {
  const res = await fetch("/api/optimize", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ rawPrompt, modelId, modeId }),
  });
  if (!res.ok) {
    let detail = "";
    try { const j = await res.json(); detail = j?.error || ""; } catch (e) {}
    const err = new Error("Proxy " + res.status + (detail ? ": " + detail : ""));
    err.code = res.status === 500 && /key/i.test(detail) ? "NO_BACKEND" : "API";
    throw err;
  }
  const data = await res.json();
  if (!data || !data.text) throw new Error("empty response");
  return data.text;
}

function hasBuiltinAI() { return !!(window.claude && window.claude.complete); }

async function optimizePrompt(rawPrompt, modelId, modeId) {
  if (hasBuiltinAI()) {
    const meta = window.buildMetaPrompt(rawPrompt, modelId, modeId);
    const out = await window.claude.complete({ messages: [{ role: "user", content: meta }] });
    return window.cleanOutput(out);
  }
  // Server builds the meta-prompt and cleans the output; we just pass the inputs.
  return await callProxy(rawPrompt, modelId, modeId);
}

Object.assign(window, { optimizePrompt, hasBuiltinAI });
