/* Unified KCC API client — wires every Cloudflare Pages Function under /api/*.
   All keys (KEEPA_KEY, ANTHROPIC_KEY, GEMINI_API_KEY, RESEND_API_KEY, SPAPI_*)
   live in Cloudflare secrets; this client never reads env vars directly.

   Exposed as window.kccAPI = { keepa, anthropic, gemini, jarvis, amazon, email,
                                 dailyPicks, rainforest, audit, sql, sync,
                                 catalogScanner, supplierHunter, findProductImage,
                                 receiptOCR, calendarICS, discover, authCode }.

   Each method returns a Promise<json>. Errors throw with a useful message.
*/

const KCC_API_BASE = ""; // same-origin; functions/api/* on Cloudflare Pages

async function kccCall(path, { method = "GET", body, query, headers } = {}) {
  const qs = query ? "?" + new URLSearchParams(query).toString() : "";
  const opts = { method, headers: { ...(headers || {}) } };
  if (body != null) {
    opts.headers["Content-Type"] = opts.headers["Content-Type"] || "application/json";
    opts.body = typeof body === "string" ? body : JSON.stringify(body);
  }
  const resp = await fetch(`${KCC_API_BASE}${path}${qs}`, opts);
  const text = await resp.text();
  let data; try { data = text ? JSON.parse(text) : {}; } catch { data = { raw: text }; }
  if (!resp.ok) {
    const msg = data?.error || data?.message || `HTTP ${resp.status} on ${path}`;
    const err = new Error(msg);
    err.status = resp.status; err.body = data;
    throw err;
  }
  return data;
}

window.kccAPI = {
  // ─── KEEPA (Amazon price/BSR history, cached 24h server-side) ─────────────
  keepa: (asin) => kccCall("/api/keepa", { query: { asin } }),

  // ─── ANTHROPIC (Claude) ──────────────────────────────────────────────────
  anthropic: ({ model = "claude-sonnet-4-6", system, messages, max_tokens = 1024, tools }) =>
    kccCall("/api/anthropic", { method: "POST", body: { model, system, messages, max_tokens, tools } }),

  // ─── GEMINI (via JARVIS proxy) ───────────────────────────────────────────
  gemini: ({ prompt, model = "gemini-2.5-flash", context }) =>
    kccCall("/api/jarvis-gemini", { method: "POST", body: { prompt, model, context } }),

  // ─── JARVIS — agentic action runner ──────────────────────────────────────
  jarvis: {
    action: (action) => kccCall("/api/jarvis-action", { method: "POST", body: action }),
    workersAI: (payload) => kccCall("/api/jarvis-workers-ai", { method: "POST", body: payload }),
  },

  // ─── AMAZON SP-API (real seller data) ────────────────────────────────────
  amazon: {
    test:      () => kccCall("/api/amazon/test"),
    finance:   (query) => kccCall("/api/amazon/finance", { query }),
    inventory: (query) => kccCall("/api/amazon/inventory", { query }),
    orders:    (query) => kccCall("/api/amazon/orders", { query }),
    hunter:    (query) => kccCall("/api/amazon/hunter", { query }),
  },

  // ─── EMAIL (Resend) ──────────────────────────────────────────────────────
  email: {
    send:        (payload) => kccCall("/api/email/send", { method: "POST", body: payload }),
    dailyDigest: (payload) => kccCall("/api/email/daily-digest", { method: "POST", body: payload }),
  },

  // ─── DAILY PICKS pipeline ────────────────────────────────────────────────
  dailyPicks: {
    fetch:      () => kccCall("/api/daily-picks"),
    production: () => kccCall("/api/daily-picks-production"),
    real:       () => kccCall("/api/daily-picks-real"),
  },

  // ─── Rainforest (Amazon product data) ────────────────────────────────────
  rainforest: (query) => kccCall("/api/rainforest", { query }),

  // ─── SQL / D1 audit / sync ────────────────────────────────────────────────
  sql:   (query) => kccCall("/api/sql", { method: "POST", body: { query } }),
  audit: () => kccCall("/api/audit"),
  sync: {
    pull: () => kccCall("/api/sync"),
    push: (payload) => kccCall("/api/sync", { method: "PUT", body: payload }),
    prefGet: (key) => kccCall(`/api/sync/prefs/${encodeURIComponent(key)}`),
    prefSet: (key, value) => kccCall(`/api/sync/prefs/${encodeURIComponent(key)}`, { method: "PUT", body: { value } }),
  },

  // ─── Sourcing helpers ────────────────────────────────────────────────────
  catalogScanner:   (payload) => kccCall("/api/catalog-scanner",   { method: "POST", body: payload }),
  supplierHunter:   (payload) => kccCall("/api/supplier-hunter",   { method: "POST", body: payload }),
  supplierByBrand:  (brand)   => kccCall("/api/supplier-hunter",   { method: "POST", body: { brand } }),
  findProductImage: (query)   => kccCall("/api/find-product-image", { query }),
  receiptOCR:       (payload) => kccCall("/api/receipt-ocr",       { method: "POST", body: payload }),

  // ─── Misc ─────────────────────────────────────────────────────────────────
  calendarICS: () => kccCall("/api/calendar/ics"),
  discover: {
    feed: () => kccCall("/api/discover/feed"),
    run:  (payload) => kccCall("/api/discover/run", { method: "POST", body: payload }),
  },
  authCode: (payload) => kccCall("/api/auth/code", { method: "POST", body: payload }),
};

// Convenience: connectivity probe used by the Settings · Intégrations tab
window.kccAPI.probe = async () => {
  const checks = [
    ["keepa",     () => window.kccAPI.keepa("B00FLYWNYQ").then(() => "ok")],
    ["anthropic", () => window.kccAPI.anthropic({ messages: [{ role: "user", content: "ping" }], max_tokens: 5 }).then(() => "ok")],
    ["gemini",    () => window.kccAPI.gemini({ prompt: "ping" }).then(() => "ok")],
    ["amazon",    () => window.kccAPI.amazon.test().then(() => "ok")],
    ["sync",      () => window.kccAPI.sync.pull().then(() => "ok")],
  ];
  const out = {};
  for (const [name, fn] of checks) {
    try { out[name] = await fn(); }
    catch (e) { out[name] = `err: ${e.message || e}`; }
  }
  return out;
};
