// src/connectors-cli.ts
var CONNECTORS_OUTPUT_FORMATS = ["text", "markdown", "json"];
function parseConnectorsFormat(value, defaultFormat = "text") {
  if (value === void 0 || value === null) return defaultFormat;
  if (typeof value !== "string" || !CONNECTORS_OUTPUT_FORMATS.includes(value)) {
    throw new Error(
      `--format expects one of ${CONNECTORS_OUTPUT_FORMATS.join(", ")}; got ${JSON.stringify(value)}`
    );
  }
  return value;
}
function parseConnectorsListOptions(options) {
  return {
    format: parseConnectorsFormat(options.format, "text")
  };
}
function parseConnectorsStatusOptions(options) {
  return {
    format: parseConnectorsFormat(options.format, "json")
  };
}
function parseConnectorsRunName(rawName) {
  if (typeof rawName !== "string" || rawName.trim().length === 0) {
    throw new Error(
      "connectors run: <name> is required and must be a non-empty connector id"
    );
  }
  return rawName.trim();
}
function statusLabel(status) {
  switch (status) {
    case "never":
      return "never synced";
    case "success":
      return "ok";
    case "error":
      return "error";
    default:
      return status;
  }
}
function fmtTimestamp(value, fallback = "\u2014") {
  if (!value) return fallback;
  return value;
}
function renderConnectorsList(rows, format) {
  if (format === "json") {
    const out = rows.map((row) => ({
      id: row.id,
      displayName: row.displayName,
      enabled: row.enabled,
      lastSyncAt: row.state?.lastSyncAt ?? null,
      lastSyncStatus: row.state?.lastSyncStatus ?? "never",
      lastSyncError: row.state?.lastSyncError ?? null,
      totalDocsImported: row.state?.totalDocsImported ?? 0,
      updatedAt: row.state?.updatedAt ?? null
    }));
    return JSON.stringify(out, null, 2);
  }
  if (rows.length === 0) {
    if (format === "markdown") {
      return "# Live connectors\n\n_No live connectors are configured._\n";
    }
    return "No live connectors configured.";
  }
  if (format === "markdown") {
    const lines2 = ["# Live connectors", ""];
    lines2.push("| ID | Display name | Enabled | Last poll | Docs imported | Status |");
    lines2.push("| --- | --- | --- | --- | --- | --- |");
    for (const row of rows) {
      const lastPoll = fmtTimestamp(row.state?.lastSyncAt);
      const docs = row.state?.totalDocsImported ?? 0;
      const status = statusLabel(row.state?.lastSyncStatus ?? "never");
      lines2.push(
        `| \`${row.id}\` | ${row.displayName} | ${row.enabled ? "yes" : "no"} | ${lastPoll} | ${docs} | ${status} |`
      );
      if (row.state?.lastSyncError) {
        lines2.push(
          `| | | | | | _Error: ${escapePipes(row.state.lastSyncError)}_ |`
        );
      }
    }
    return lines2.join("\n") + "\n";
  }
  const lines = [`Live connectors (${rows.length}):`];
  lines.push("");
  for (const row of rows) {
    const enabledStr = row.enabled ? "enabled" : "disabled";
    const status = statusLabel(row.state?.lastSyncStatus ?? "never");
    const lastPoll = fmtTimestamp(row.state?.lastSyncAt, "(never polled)");
    const docs = row.state?.totalDocsImported ?? 0;
    lines.push(`  ${row.id}  (${row.displayName})`);
    lines.push(`    state:         ${enabledStr}, ${status}`);
    lines.push(`    last_poll:     ${lastPoll}`);
    lines.push(`    docs_imported: ${docs}`);
    if (row.state?.lastSyncError) {
      lines.push(`    last_error:    ${row.state.lastSyncError}`);
    }
  }
  return lines.join("\n");
}
function renderConnectorsRunResult(connectorId, result, format) {
  const ok = result.error === void 0 && result.stateWriteError === void 0;
  if (format === "json") {
    return JSON.stringify(
      {
        connector: connectorId,
        docsImported: result.docsImported,
        error: result.error ?? null,
        stateWriteError: result.stateWriteError ?? null,
        ok
      },
      null,
      2
    );
  }
  if (format === "markdown") {
    const lines2 = [`# connectors run: \`${connectorId}\``, ""];
    lines2.push(`- **Status:** ${ok ? "success" : "error"}`);
    lines2.push(`- **Docs imported:** ${result.docsImported}`);
    if (result.error !== void 0) {
      lines2.push(`- **Error:** ${result.error}`);
    }
    if (result.stateWriteError !== void 0) {
      const label = result.error === void 0 ? "State-write error (cursor not advanced)" : "State-write error (error state not persisted)";
      lines2.push(`- **${label}:** ${result.stateWriteError}`);
    }
    return lines2.join("\n") + "\n";
  }
  const lines = [];
  if (ok) {
    lines.push(`connectors run: ${connectorId} \u2014 OK`);
    lines.push(`  docs_imported: ${result.docsImported}`);
  } else {
    lines.push(`connectors run: ${connectorId} \u2014 FAILED`);
    lines.push(`  docs_imported: ${result.docsImported}`);
    if (result.error !== void 0) {
      lines.push(`  error:         ${result.error}`);
    }
    if (result.stateWriteError !== void 0) {
      lines.push(
        `  state_write_error: ${result.stateWriteError}`
      );
      if (result.error === void 0) {
        lines.push(
          result.docsImported > 0 ? `  (docs were ingested; cursor was not advanced \u2014 next poll will re-fetch from prior position)` : `  (cursor was not advanced \u2014 next poll will retry from prior position)`
        );
      } else {
        lines.push(
          `  (error state was not persisted \u2014 next poll will retry from prior position)`
        );
      }
    }
  }
  return lines.join("\n");
}
async function runConnectorPollOnce(args) {
  const { connectorId, priorState, syncFn, ingestFn, writeCursorFn } = args;
  let syncResult;
  let ingestError;
  try {
    syncResult = await syncFn(priorState?.cursor ?? null);
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    let stateWriteError;
    try {
      await writeCursorFn({
        cursor: priorState?.cursor ?? null,
        lastSyncStatus: "error",
        lastSyncError: msg,
        totalDocsImported: priorState?.totalDocsImported ?? 0
      });
    } catch (writeErr) {
      stateWriteError = writeErr instanceof Error ? writeErr.message : String(writeErr);
      console.error(
        `[remnic] connectors/${connectorId}: failed to persist error state after syncFn failure (${stateWriteError}); original error: ${msg}`
      );
    }
    return {
      docsImported: 0,
      error: msg,
      ...stateWriteError !== void 0 ? { stateWriteError } : {}
    };
  }
  if (syncResult.newDocs.length > 0) {
    try {
      await ingestFn(syncResult.newDocs);
    } catch (err) {
      ingestError = err instanceof Error ? err.message : String(err);
    }
  }
  if (ingestError !== void 0) {
    let stateWriteError;
    try {
      await writeCursorFn({
        cursor: priorState?.cursor ?? null,
        lastSyncStatus: "error",
        lastSyncError: ingestError,
        totalDocsImported: priorState?.totalDocsImported ?? 0
      });
    } catch (writeErr) {
      stateWriteError = writeErr instanceof Error ? writeErr.message : String(writeErr);
      console.error(
        `[remnic] connectors/${connectorId}: failed to persist error state after ingestFn failure (${stateWriteError}); original error: ${ingestError}`
      );
    }
    return {
      docsImported: 0,
      error: ingestError,
      ...stateWriteError !== void 0 ? { stateWriteError } : {}
    };
  }
  const docsImported = syncResult.newDocs.length;
  try {
    await writeCursorFn({
      cursor: syncResult.nextCursor,
      lastSyncStatus: "success",
      totalDocsImported: (priorState?.totalDocsImported ?? 0) + docsImported
    });
  } catch (writeErr) {
    const writeMsg = writeErr instanceof Error ? writeErr.message : String(writeErr);
    return { docsImported, stateWriteError: writeMsg };
  }
  return { docsImported };
}
function escapePipes(value) {
  return value.replace(/\\/g, "\\\\").replace(/\|/g, "\\|");
}

export {
  CONNECTORS_OUTPUT_FORMATS,
  parseConnectorsFormat,
  parseConnectorsListOptions,
  parseConnectorsStatusOptions,
  parseConnectorsRunName,
  renderConnectorsList,
  renderConnectorsRunResult,
  runConnectorPollOnce
};
//# sourceMappingURL=chunk-OZHRDTDX.js.map