// Observability API — the audit trail of knowledge-service asks shown on the
// org Observability → Retrievals tab. One row per stored assistant turn of the
// knowledge agent (console chat, ask-parcle skill, MCP — everything that goes
// through /skill/ask*).
//
//   GET /skill/retrievals?page&limit → {retrievals, page, total_pages, total}
//   GET /skill/retrievals/{turn_id}  → list row + full sanitized AskResponse
//   GET /skill/retrievals/stats?days → {days, total, by_status, latency_*, daily}
//
// Latency is computed server-side from the turn's recorded LLM + tool call
// latencies. There is no mock fallback: without a configured backend the
// Observability tabs surface the fetch error.

// FastAPI's `detail` is a string for HTTPException but a list of error objects
// for a 422 validation failure — stringifying that blindly renders
// "[object Object]" in the error card, so only a string is used as-is.
function _parcleDetailText(detail) {
  if (typeof detail === 'string') return detail;
  if (Array.isArray(detail)) return detail.map(d => (d && d.msg) || '').filter(Boolean).join('; ');
  return '';
}

async function _parcleRetrievalsGet(path) {
  const res = await fetch(parcleApiBase() + path, { headers: parcleAuthHeaders() });
  if (res.status === 401 && typeof parcleNotifyUnauthorized === 'function') parcleNotifyUnauthorized();
  if (!res.ok) {
    let detail = '';
    try { detail = _parcleDetailText((await res.json()).detail); } catch (e) { /* non-JSON body */ }
    throw new Error(detail ? `${detail} (${res.status})` : `GET ${path} → ${res.status}`);
  }
  return await res.json();
}

const ParcleRetrievalsAPI = {
  list(page, limit) {
    return _parcleRetrievalsGet(`/skill/retrievals?page=${encodeURIComponent(page)}&limit=${encodeURIComponent(limit)}`);
  },
  detail(turnId) {
    return _parcleRetrievalsGet(`/skill/retrievals/${encodeURIComponent(turnId)}`);
  },
  stats(days) {
    return _parcleRetrievalsGet(`/skill/retrievals/stats?days=${encodeURIComponent(days)}`);
  },
};

Object.assign(window, { ParcleRetrievalsAPI });
