const AI_ENDPOINTS = [
  {
    id: "ollama",
    label: "Ollama",
    installUrl: "https://ollama.com/download",
    endpoint: "http://127.0.0.1:11434/api/generate",
    buildRequest(prompt, context) {
      return {
        model: context?.model || "llama3.1",
        prompt: buildPrompt(prompt, context),
        stream: false,
        options: { temperature: 0.25, num_predict: 360 },
      };
    },
    parse(data) {
      return data?.response || "";
    },
  },
  {
    id: "lm-studio",
    label: "LM Studio",
    installUrl: "https://lmstudio.ai/download",
    endpoint: "http://127.0.0.1:1234/v1/chat/completions",
    buildRequest(prompt, context) {
      return {
        model: context?.model || "local-model",
        messages: [
          { role: "system", content: systemPrompt(context) },
          { role: "user", content: prompt },
        ],
        temperature: 0.25,
        max_tokens: 360,
      };
    },
    parse(data) {
      return data?.choices?.[0]?.message?.content || "";
    },
  },
  {
    id: "llama-cpp",
    label: "llama.cpp",
    installUrl: "https://github.com/ggml-org/llama.cpp",
    endpoint: "http://127.0.0.1:8080/completion",
    buildRequest(prompt, context) {
      return {
        prompt: buildPrompt(prompt, context),
        temperature: 0.25,
        n_predict: 360,
      };
    },
    parse(data) {
      return data?.content || data?.completion || "";
    },
  },
];

const DEFAULT_BRIDGE_URL = "https://utxo-ai-brain.inf-vestigeindex.workers.dev/api/utxo-ai/explain";

function systemPrompt(context = {}) {
  return [
    "You are UTXO AI, a local/open-source Web3 security explanation layer.",
    "You are the Answer AI. You explain scores produced by UTXO Score AI; you never invent or modify the score.",
    "Never ask for seed phrases or private keys.",
    "Never sign, execute, custody funds, or provide financial advice.",
    "Explain observable risk clearly and say when exact data is missing.",
    `Risk percent: ${context.riskPercent ?? "unknown"}%. Risk: ${context.risk || "unknown"}. Decision: ${context.decision || "review"}.`,
  ].join("\n");
}

function buildPrompt(prompt, context) {
  return `${systemPrompt(context)}\n\nUser request:\n${prompt}\n\nAnswer concisely in the user's language.`;
}

function fallbackExplanation(result, language = "en") {
  const risk = result?.risk || "medium";
  const riskPercent = result?.riskPercent ?? Math.max(0, 100 - Number(result?.score ?? 70));
  const warnings = Array.isArray(result?.warnings) ? result.warnings.slice(0, 3) : [];
  const warningText = warnings.length ? warnings.join(" ") : "No critical warning is visible from the current page scan.";

  if (String(language).toLowerCase().startsWith("es")) {
    if (risk === "critical") {
      return `Riesgo crítico (${riskPercent}%). No firmes todavía. ${warningText}`;
    }
    if (risk === "high") {
      return `Riesgo alto (${riskPercent}%). Revisa URL, permisos, ruta y prompt de wallet antes de firmar. ${warningText}`;
    }
    if (risk === "medium") {
      return `Riesgo medio (${riskPercent}%). La operación requiere revisión manual antes de firmar. ${warningText}`;
    }
    return `Riesgo bajo (${riskPercent}%). Aun así, confirma red, activo, destino e importe en tu wallet.`;
  }

  if (risk === "critical") {
    return `Critical risk (${riskPercent}%). Do not sign yet. ${warningText}`;
  }
  if (risk === "high") {
    return `High risk (${riskPercent}%). Review URL, approvals, route and wallet prompt before signing. ${warningText}`;
  }
  if (risk === "medium") {
    return `Medium risk (${riskPercent}%). Manual review is recommended before signing. ${warningText}`;
  }
  return `Low risk (${riskPercent}%). Still verify network, asset, recipient and amount in your wallet.`;
}

async function callEndpoint(provider, prompt, context) {
  const response = await fetch(provider.endpoint, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(provider.buildRequest(prompt, context)),
  });

  if (!response.ok) {
    throw new Error(`${provider.label} returned ${response.status}`);
  }

  const data = await response.json();
  const text = provider.parse(data);
  if (!text) {
    throw new Error(`${provider.label} returned an empty response`);
  }
  return text;
}

async function callBridge(result, options = {}) {
  const bridgeUrl = options.bridgeUrl || DEFAULT_BRIDGE_URL;
  const response = await fetch(bridgeUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-UTXO-Client": "utxo-guard-extension",
    },
    body: JSON.stringify({
      score: result?.score,
      riskPercent: result?.riskPercent,
      risk: result?.risk,
      decision: result?.decision,
      warnings: result?.warnings,
      layers: result?.layers?.map((item) => ({ layer: item.layer, risk: item.risk, passed: item.passed })),
      trustProfile: result?.trustProfile,
      scoringEngine: result?.scoringEngine,
      language: options.language || navigator.language || "en",
      licenseKey: options.licenseKey || "",
      productId: options.productId || "utxo-guard",
      origin: options.origin || "",
    }),
  });

  if (!response.ok) {
    throw new Error(`UTXO AI bridge returned ${response.status}`);
  }

  const data = await response.json();
  if (!data?.text) {
    throw new Error("UTXO AI bridge returned an empty response");
  }

  return {
    mode: data.mode || "cloud-bridge",
    provider: data.provider || "UTXO AI Bridge",
    text: data.text,
  };
}

async function explainWithUtxoAI(result, options = {}) {
  const prompt =
    options.prompt ||
    `Explain this UTXO Guard result for a user before they sign: ${JSON.stringify({
      score: result?.score,
      riskPercent: result?.riskPercent,
      risk: result?.risk,
      decision: result?.decision,
      warnings: result?.warnings,
      layers: result?.layers?.map((item) => ({ layer: item.layer, risk: item.risk, passed: item.passed })),
      trustProfile: result?.trustProfile,
      scoringEngine: result?.scoringEngine,
    })}`;
  const context = {
    risk: result?.risk,
    riskPercent: result?.riskPercent,
    decision: result?.decision,
    model: options.model,
  };

  for (const provider of AI_ENDPOINTS) {
    try {
      const text = await callEndpoint(provider, prompt, context);
      return {
        mode: "local-model",
        provider: provider.label,
        text,
        installUrl: provider.installUrl,
      };
    } catch {
      // Try the next local provider, then fall back safely.
    }
  }

  if (options.bridgeEnabled !== false) {
    try {
      return await callBridge(result, options);
    } catch {
      // Final safe fallback keeps the extension useful even if the bridge is offline.
    }
  }

  return {
    mode: "safe-fallback",
    provider: "UTXO Safe Fallback",
    text: fallbackExplanation(result, options.language || navigator.language || "en"),
    installOptions: AI_ENDPOINTS.map(({ label, installUrl }) => ({ label, installUrl })),
  };
}

self.UTXO_AI_ENDPOINTS = AI_ENDPOINTS;
self.explainWithUtxoAI = explainWithUtxoAI;

