"use client";
import { buildLambdaApiUrl } from './chunk-SYNVNTLJ.mjs';
import { HttpResponseError } from '@datatechsolutions/shared-domain/common';

var _authFetch = fetch;
function setAuthenticatedFetch(authFetch) {
  _authFetch = authFetch;
}
var _tokenProvider = async () => null;
function setAccessTokenProvider(provider) {
  _tokenProvider = provider;
}
async function getCurrentAccessToken() {
  try {
    return await _tokenProvider();
  } catch {
    return null;
  }
}
async function buildAuthenticatedApiUrl(path, options = {}) {
  const baseUrl = useExternalWorkflowApi() ? resolveWorkflowApiBaseUrl() : buildLambdaApiUrl("").replace(/\/$/, "");
  const url = new URL(`${baseUrl}${path}`);
  if (options.includeAccessToken) {
    const token = await getCurrentAccessToken();
    if (token && token.length > 0) {
      url.searchParams.set("accessToken", token);
    }
  }
  return url.toString();
}
function useExternalWorkflowApi() {
  return import.meta.env.VITE_WORKFLOW_API_MODE === "external";
}
function resolveWorkflowApiBaseUrl() {
  const baseUrl = import.meta.env.VITE_WORKFLOW_API_BASE_URL;
  if (!baseUrl || baseUrl.trim().length === 0) {
    throw new Error("Missing VITE_WORKFLOW_API_BASE_URL for external workflow API mode");
  }
  return baseUrl.replace(/\/$/, "");
}
function getPublishableKey() {
  const key = import.meta.env.VITE_WORKFLOW_BUILDER_PUBLISHABLE_KEY;
  if (!key || key.trim().length === 0) {
    throw new Error("Missing VITE_WORKFLOW_BUILDER_PUBLISHABLE_KEY");
  }
  return key;
}
async function request(path, init) {
  const publishableKey = useExternalWorkflowApi() ? getPublishableKey() : null;
  const baseUrl = publishableKey ? resolveWorkflowApiBaseUrl() : buildLambdaApiUrl("").replace(/\/$/, "");
  const headers = {
    "Content-Type": "application/json"
  };
  if (publishableKey) {
    headers.Authorization = `Bearer ${publishableKey}`;
    headers["X-Workflow-Key"] = publishableKey;
  }
  const response = await _authFetch(`${baseUrl}${path}`, {
    ...init,
    credentials: init?.credentials ?? "include",
    headers: { ...headers, ...init?.headers }
  });
  if (response.status === 204) return void 0;
  const payload = await response.json().catch(() => null);
  if (!response.ok) {
    const message = payload?.message ?? payload?.error ?? `HTTP ${response.status}: ${response.statusText}`;
    throw new HttpResponseError(message, response.status);
  }
  if (payload && typeof payload === "object" && "data" in payload && (!("success" in payload) || payload.success !== false)) {
    return payload.data;
  }
  return payload;
}
async function requestPublic(path, init) {
  const externalBaseUrl = import.meta.env.VITE_WORKFLOW_API_BASE_URL?.trim();
  const baseUrl = externalBaseUrl && externalBaseUrl.length > 0 ? externalBaseUrl.replace(/\/$/, "") : buildLambdaApiUrl("").replace(/\/$/, "");
  const response = await fetch(`${baseUrl}${path}`, {
    ...init,
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      ...init?.headers
    }
  });
  if (response.status === 204) return void 0;
  const payload = await response.json().catch(() => null);
  if (!response.ok) {
    const message = payload?.message ?? payload?.error ?? `HTTP ${response.status}: ${response.statusText}`;
    throw new HttpResponseError(message, response.status);
  }
  if (payload && typeof payload === "object" && "success" in payload && payload.success && "data" in payload) {
    return payload.data;
  }
  return payload;
}
async function aiValidateWorkflow(body) {
  return request("/workflows/validate/ai", {
    method: "POST",
    body: JSON.stringify(body)
  });
}
async function aiGenerateWorkflow(body) {
  return request("/workflows/generate/ai", {
    method: "POST",
    body: JSON.stringify(body)
  });
}
async function getWorkflows() {
  return request("/workflows");
}
async function getWorkflowById(workflowId) {
  return request(`/workflows/${encodeURIComponent(workflowId)}`);
}
async function createWorkflow(data) {
  return request("/workflows", {
    method: "POST",
    body: JSON.stringify(data)
  });
}
async function deleteWorkflow(workflowId) {
  return request(`/workflows/${encodeURIComponent(workflowId)}`, {
    method: "DELETE"
  });
}
async function saveWorkflowDraft(workflowId, graph, metadata) {
  return request(`/workflows/${encodeURIComponent(workflowId)}`, {
    method: "PATCH",
    body: JSON.stringify({ graph, ...metadata })
  });
}
async function updateWorkflowSettings(workflowId, changes) {
  return request(`/workflows/${encodeURIComponent(workflowId)}`, {
    method: "PATCH",
    body: JSON.stringify(changes)
  });
}
async function publishWorkflow(workflowId) {
  return request(`/workflows/${encodeURIComponent(workflowId)}/publish`, {
    method: "POST"
  });
}
async function executeWorkflow(workflowId, inputVariables) {
  return request(`/workflows/${encodeURIComponent(workflowId)}/execute`, {
    method: "POST",
    body: JSON.stringify({ inputVariables: inputVariables ?? {} })
  });
}
async function getWorkflowRuns(workflowId) {
  return request(`/workflows/${encodeURIComponent(workflowId)}/execute`);
}
async function listWorkflowTemplates() {
  return request("/workflows/templates");
}
async function createWorkflowFromTemplate(templateId, body) {
  return request(`/workflows/templates/${encodeURIComponent(templateId)}`, {
    method: "POST",
    body: JSON.stringify(body)
  });
}
async function listModelProviderConnections() {
  return request("/agents/connections");
}
async function listModelProviderCatalog() {
  const response = await request(
    "/agents/providers"
  );
  if (Array.isArray(response)) return response;
  if (response && typeof response === "object" && Array.isArray(response.data)) {
    return response.data;
  }
  return [];
}
async function createModelProviderConnection(body) {
  return request("/agents/connections", {
    method: "POST",
    body: JSON.stringify(body)
  });
}
async function updateModelProviderConnection(id, body) {
  return request(`/agents/connections/${encodeURIComponent(id)}`, {
    method: "PATCH",
    body: JSON.stringify(body)
  });
}
async function deleteModelProviderConnection(id) {
  return request(`/agents/connections/${encodeURIComponent(id)}`, {
    method: "DELETE"
  });
}
async function getAgentPrompts(agentId) {
  return request(`/agents/prompts?agentId=${encodeURIComponent(agentId)}`);
}
async function getAgentModels() {
  return request("/agents/models");
}
async function getAgentTools(agentId) {
  return request(`/agents/tools?agentId=${encodeURIComponent(agentId)}`);
}
async function updateAgentTool(toolId, updates) {
  const wire = { id: toolId };
  if (typeof updates.enabled === "boolean") wire.isEnabled = updates.enabled;
  const overrides = updates.configOverrides;
  if (overrides !== void 0) wire.configOverrides = overrides;
  return request("/agents/tools", {
    method: "PATCH",
    body: JSON.stringify(wire)
  });
}
async function createAgentTool(tool) {
  return request("/agents/tools", {
    method: "POST",
    body: JSON.stringify(tool)
  });
}
async function deleteAgentTool(toolId) {
  return request(`/agents/tools/${encodeURIComponent(toolId)}`, {
    method: "DELETE"
  });
}
async function getAgentToolDefinitions() {
  return request("/agents/tool-definitions");
}
async function createAgentToolDefinition(toolDef) {
  return request("/agents/tool-definitions", {
    method: "POST",
    body: JSON.stringify(toolDef)
  });
}
async function getAgentRules() {
  const response = await request("/rules");
  if (Array.isArray(response)) return response;
  if (response && typeof response === "object" && Array.isArray(response.data)) {
    return response.data;
  }
  return [];
}
async function updateAgentRule(ruleId, updates) {
  return request(`/rules/${encodeURIComponent(ruleId)}`, {
    method: "PATCH",
    body: JSON.stringify(updates)
  });
}
async function createAgentRule(rule) {
  return request("/rules", {
    method: "POST",
    body: JSON.stringify(rule)
  });
}
async function deleteAgentRule(ruleId) {
  return request(`/rules/${encodeURIComponent(ruleId)}`, {
    method: "DELETE"
  });
}
async function executeAgentRule(ruleId, input) {
  return request(`/rules/${encodeURIComponent(ruleId)}/execute`, {
    method: "POST",
    body: JSON.stringify(input)
  });
}
async function createAgentConfig(input) {
  return request("/agents/configs", {
    method: "POST",
    body: JSON.stringify(input)
  });
}
async function updateAgentConfig(agentId, updates) {
  return request(`/agents/configs/${encodeURIComponent(agentId)}`, {
    method: "PATCH",
    body: JSON.stringify(updates)
  });
}
async function deleteAgentConfig(agentId) {
  return request(`/agents/configs/${encodeURIComponent(agentId)}`, {
    method: "DELETE"
  });
}
async function createAgentPrompt(input) {
  return request("/agents/prompts", {
    method: "POST",
    body: JSON.stringify(input)
  });
}
async function updateAgentPrompt(promptId, updates) {
  const promptText = updates.promptText ?? updates.systemPrompt ?? updates.content;
  if (typeof promptText !== "string" || promptText.length === 0) {
    throw new Error("updateAgentPrompt: `promptText` (or `systemPrompt`/`content`) is required");
  }
  return request("/agents/prompts", {
    method: "PATCH",
    body: JSON.stringify({ promptId, promptText })
  });
}
async function deleteAgentPrompt(promptId) {
  throw new Error("deleteAgentPrompt is not supported by the backend yet \u2014 disable the prompt via PATCH instead");
}
async function updateAgentToolDefinition(agentToolId, updates) {
  return request("/agents/tool-definitions", {
    method: "PATCH",
    body: JSON.stringify({ toolId: agentToolId, ...updates })
  });
}
async function deleteAgentToolDefinition(agentToolId) {
  return request("/agents/tool-definitions", {
    method: "DELETE",
    body: JSON.stringify({ toolId: agentToolId })
  });
}
async function listWorkflowRuns(params) {
  const query = new URLSearchParams();
  if (params?.workflowId) query.set("workflowId", params.workflowId);
  if (params?.status) query.set("status", params.status);
  if (params?.limit) query.set("limit", String(params.limit));
  if (params?.offset) query.set("offset", String(params.offset));
  const path = query.toString().length > 0 ? `/workflow-runs?${query}` : "/workflow-runs";
  return request(path);
}
async function getWorkflowRunById(runId) {
  return request(`/workflow-runs/${encodeURIComponent(runId)}`);
}
async function cancelWorkflowRun(runId) {
  return request(`/workflow-runs/${encodeURIComponent(runId)}/cancel`, {
    method: "POST"
  });
}
async function replayWorkflowRun(workflowId, runId, overrides) {
  const body = overrides && Object.keys(overrides).length > 0 ? JSON.stringify({ inputVariables: overrides }) : void 0;
  return request(
    `/workflows/${encodeURIComponent(workflowId)}/runs/${encodeURIComponent(runId)}/replay`,
    { method: "POST", body }
  );
}
async function getRunTimeline(workflowId, runId) {
  return request(
    `/workflows/${encodeURIComponent(workflowId)}/runs/${encodeURIComponent(runId)}/timeline`
  );
}
async function getAnalyticsSummary(params) {
  const query = new URLSearchParams();
  if (params?.from) query.set("from", params.from);
  if (params?.to) query.set("to", params.to);
  const path = query.toString().length > 0 ? `/analytics/runs?${query}` : "/analytics/runs";
  return request(path);
}
async function presignUpload(input) {
  return request("/uploads", {
    method: "POST",
    body: JSON.stringify(input)
  });
}
async function getUploadDownloadUrl(objectKey) {
  return request(`/uploads/${encodeURIComponent(objectKey)}`);
}
async function deleteUpload(objectKey) {
  return request(`/uploads/${encodeURIComponent(objectKey)}`, {
    method: "DELETE"
  });
}
async function getPublicSampleWorkflow(slug) {
  return requestPublic(`/samples/workflows/${encodeURIComponent(slug)}`);
}
async function submitApproval(runId, nodeId, decision) {
  return request(
    `/workflow-runs/${encodeURIComponent(runId)}/approvals/${encodeURIComponent(nodeId)}`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(decision)
    }
  );
}
var SSE_MAX_RECONNECT_ATTEMPTS = 5;
var SSE_RECONNECT_BASE_MS = 1e3;
var SSE_RECONNECT_CAP_MS = 16e3;
var POLLING_INTERVAL_MS = 5e3;
var TERMINAL_EVENT_TYPES = /* @__PURE__ */ new Set([
  "run-completed",
  "run-failed"
]);
var TERMINAL_RUN_STATUSES = /* @__PURE__ */ new Set([
  "completed",
  "failed",
  "cancelled"
]);
function subscribeToRunEvents(runId, onEvent, onError, onState) {
  let cancelled = false;
  let attempt = 0;
  let currentSource = null;
  let reconnectTimer = null;
  let pollingTimer = null;
  const setState = (state) => {
    if (!cancelled) onState?.(state);
  };
  const cleanup = () => {
    if (cancelled) return;
    cancelled = true;
    if (currentSource) {
      currentSource.close();
      currentSource = null;
    }
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
      reconnectTimer = null;
    }
    if (pollingTimer) {
      clearInterval(pollingTimer);
      pollingTimer = null;
    }
    setState("closed");
  };
  const startPolling = () => {
    if (cancelled) return;
    setState("polling");
    pollingTimer = setInterval(() => {
      if (cancelled) return;
      void getWorkflowRunById(runId).then((run) => {
        if (cancelled) return;
        onEvent({
          type: "log",
          runId,
          data: { source: "polling-fallback", run },
          timestamp: (/* @__PURE__ */ new Date()).toISOString()
        });
        if (run.status && TERMINAL_RUN_STATUSES.has(run.status)) {
          cleanup();
        }
      }).catch(() => {
      });
    }, POLLING_INTERVAL_MS);
  };
  const connect = () => {
    if (cancelled) return;
    const baseUrl = buildLambdaApiUrl("").replace(/\/$/, "");
    const url = `${baseUrl}/workflow-runs/${encodeURIComponent(runId)}/events`;
    const source = new EventSource(url, { withCredentials: true });
    currentSource = source;
    source.addEventListener("open", () => {
      attempt = 0;
      setState("live");
    });
    source.addEventListener("message", (event) => {
      try {
        const parsed = JSON.parse(event.data);
        onEvent(parsed);
        if (TERMINAL_EVENT_TYPES.has(parsed.type)) {
          cleanup();
        }
      } catch {
      }
    });
    source.addEventListener("error", (errorEvent) => {
      if (cancelled) return;
      onError?.(errorEvent);
      source.close();
      currentSource = null;
      attempt += 1;
      if (attempt > SSE_MAX_RECONNECT_ATTEMPTS) {
        startPolling();
        return;
      }
      const exponentialMs = Math.min(SSE_RECONNECT_BASE_MS * 2 ** (attempt - 1), SSE_RECONNECT_CAP_MS);
      const jitterMs = Math.random() * 500;
      setState("reconnecting");
      reconnectTimer = setTimeout(connect, exponentialMs + jitterMs);
    });
  };
  connect();
  return cleanup;
}
var AGENT_AVATARS = {
  "Sales Assistant": "https://api.dicebear.com/9.x/lorelei/svg?seed=Rafael&hair=variant01&beardProbability=0&mouth=happy01",
  "Sales Specialist": "https://api.dicebear.com/9.x/lorelei/svg?seed=Marcos&hair=variant15&beardProbability=50&mouth=happy02",
  "Support Agent": "https://api.dicebear.com/9.x/lorelei/svg?seed=Ana&hair=variant43&beardProbability=0&mouth=happy01",
  "Financial Analyst": "https://api.dicebear.com/9.x/lorelei/svg?seed=Lucas&hair=variant08&beardProbability=50&mouth=happy02",
  "Security Analyst": "https://api.dicebear.com/9.x/lorelei/svg?seed=Pedro&hair=variant22&beardProbability=50&mouth=happy01",
  "Data Analyst": "https://api.dicebear.com/9.x/lorelei/svg?seed=Julia&hair=variant29&beardProbability=0&mouth=happy01",
  "Market Analyst": "https://api.dicebear.com/9.x/lorelei/svg?seed=Diego&hair=variant12&beardProbability=0&mouth=happy02",
  "Pricing Manager": "https://api.dicebear.com/9.x/lorelei/svg?seed=Beatriz&hair=variant38&beardProbability=0&mouth=happy01",
  "Onboarding Agent": "https://api.dicebear.com/9.x/lorelei/svg?seed=Camila&hair=variant35&beardProbability=0&mouth=happy01"
};
function defaultAvatar(name) {
  return AGENT_AVATARS[name] ?? `https://api.dicebear.com/9.x/lorelei/svg?seed=${encodeURIComponent(name)}`;
}
async function getAgentConfigsWithPrompts() {
  const configs = await request("/agents/configs");
  return Promise.all(configs.map(async (agent) => {
    const raw = agent;
    const agentId = String(raw.agent_id ?? raw.agentId ?? agent.id ?? "");
    const id = agentId;
    const avatar = typeof raw.avatar === "string" && raw.avatar.length > 0 ? raw.avatar : defaultAvatar(String(agent.name ?? ""));
    const modelId = String(raw.model_id ?? raw.modelId ?? "");
    const displayOrder = Number(raw.display_order ?? raw.displayOrder ?? raw.order ?? 0);
    const maxTokens = Number(raw.max_tokens ?? raw.maxTokens ?? 2048);
    const normalized = { ...raw, agentId, modelId, displayOrder, maxTokens, order: displayOrder };
    if (!id) return { ...normalized, avatar, promptCount: 0, activePromptVersion: 0 };
    try {
      const prompts = await getAgentPrompts(id);
      const activePrompt = prompts.find((prompt) => prompt.isActive);
      return {
        ...normalized,
        avatar,
        promptCount: prompts.length,
        activePromptVersion: activePrompt?.version ?? 0
      };
    } catch {
      return {
        ...normalized,
        avatar,
        promptCount: 0,
        activePromptVersion: 0
      };
    }
  }));
}
async function getDatasources() {
  return request("/datasources");
}
async function createDatasource(data) {
  const body = toDatasourceWireBody(data);
  return request("/datasources", {
    method: "POST",
    body: JSON.stringify(body)
  });
}
function toDatasourceWireBody(data) {
  const CREDENTIAL_KEYS = [
    "host",
    "port",
    "database",
    "username",
    "password",
    "schema",
    "connectionString",
    "projectId",
    "dataset",
    "keyFile",
    "account",
    "warehouse",
    "region",
    "bucket",
    "token",
    "apiKey",
    "environment",
    "index",
    "url",
    "ssl"
  ];
  const credentials = {};
  for (const key of CREDENTIAL_KEYS) {
    const value = data[key];
    if (value !== void 0 && value !== "" && value !== null) {
      credentials[key] = value;
    }
  }
  const body = {
    name: data.name,
    dialect: data.dialect
  };
  if (Object.keys(credentials).length > 0) body.credentials = credentials;
  if (data.allowedTables && data.allowedTables.length > 0) body.allowedTables = data.allowedTables;
  if (data.blockedColumns && data.blockedColumns.length > 0) body.blockedColumns = data.blockedColumns;
  if (typeof data.maxPoolSize === "number") body.maxPoolSize = data.maxPoolSize;
  if (typeof data.timeoutMs === "number") body.timeoutMs = data.timeoutMs;
  if (typeof data.readOnly === "boolean") body.readOnly = data.readOnly;
  return body;
}
async function getDatasourceTables(datasourceId) {
  return request(`/datasources/${encodeURIComponent(datasourceId)}/tables`);
}
async function getDatasourceSchema(datasourceId, table) {
  return request(`/datasources/${encodeURIComponent(datasourceId)}/schema/${encodeURIComponent(table)}`);
}

export { aiGenerateWorkflow, aiValidateWorkflow, buildAuthenticatedApiUrl, cancelWorkflowRun, createAgentConfig, createAgentPrompt, createAgentRule, createAgentTool, createAgentToolDefinition, createDatasource, createModelProviderConnection, createWorkflow, createWorkflowFromTemplate, deleteAgentConfig, deleteAgentPrompt, deleteAgentRule, deleteAgentTool, deleteAgentToolDefinition, deleteModelProviderConnection, deleteUpload, deleteWorkflow, executeAgentRule, executeWorkflow, getAgentConfigsWithPrompts, getAgentModels, getAgentPrompts, getAgentRules, getAgentToolDefinitions, getAgentTools, getAnalyticsSummary, getCurrentAccessToken, getDatasourceSchema, getDatasourceTables, getDatasources, getPublicSampleWorkflow, getRunTimeline, getUploadDownloadUrl, getWorkflowById, getWorkflowRunById, getWorkflowRuns, getWorkflows, listModelProviderCatalog, listModelProviderConnections, listWorkflowRuns, listWorkflowTemplates, presignUpload, publishWorkflow, replayWorkflowRun, saveWorkflowDraft, setAccessTokenProvider, setAuthenticatedFetch, submitApproval, subscribeToRunEvents, updateAgentConfig, updateAgentPrompt, updateAgentRule, updateAgentTool, updateAgentToolDefinition, updateModelProviderConnection, updateWorkflowSettings };
//# sourceMappingURL=chunk-ZV5EZXXO.mjs.map
//# sourceMappingURL=chunk-ZV5EZXXO.mjs.map