// src/capsule-cli.ts
import path from "path";
function parseCapsuleOutputFormat(raw) {
  if (raw === void 0 || raw === null) return "text";
  if (typeof raw !== "string" || raw.trim() === "") {
    throw new Error(
      `--format expects one of text, markdown, json; got ${JSON.stringify(raw)}`
    );
  }
  const v = raw.trim();
  if (v !== "text" && v !== "markdown" && v !== "json") {
    throw new Error(
      `--format expects one of text, markdown, json; got ${JSON.stringify(raw)}`
    );
  }
  return v;
}
function parseCapsuleImportMode(raw) {
  if (raw === void 0 || raw === null) return "skip";
  if (typeof raw !== "string" || raw.trim() === "") {
    throw new Error(
      `--mode expects one of skip, overwrite, fork; got ${JSON.stringify(raw)}`
    );
  }
  const v = raw.trim();
  if (v !== "skip" && v !== "overwrite" && v !== "fork") {
    throw new Error(
      `--mode expects one of skip, overwrite, fork; got ${JSON.stringify(raw)}`
    );
  }
  return v;
}
function parseCapsuleConflictMode(raw) {
  if (raw === void 0 || raw === null) return "skip-conflicts";
  if (typeof raw !== "string" || raw.trim() === "") {
    throw new Error(
      `--conflict-mode expects one of skip-conflicts, prefer-source, prefer-local; got ${JSON.stringify(raw)}`
    );
  }
  const v = raw.trim();
  if (v !== "skip-conflicts" && v !== "prefer-source" && v !== "prefer-local") {
    throw new Error(
      `--conflict-mode expects one of skip-conflicts, prefer-source, prefer-local; got ${JSON.stringify(raw)}`
    );
  }
  return v;
}
var ISO_8601_RE = /^\d{4}-\d{2}-\d{2}(?:[Tt]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:[Zz]|[+-]\d{2}:?\d{2}))?$/;
function parseCapsuleSince(raw) {
  if (raw === void 0 || raw === null) return void 0;
  if (typeof raw !== "string") {
    throw new Error(
      `--since expects an ISO 8601 timestamp; got ${JSON.stringify(raw)}`
    );
  }
  if (raw.trim() === "") {
    throw new Error(`--since expects an ISO 8601 timestamp; received empty string`);
  }
  if (!ISO_8601_RE.test(raw)) {
    throw new Error(
      `--since is not a valid ISO 8601 timestamp: ${raw}. Accepted forms: YYYY-MM-DD, YYYY-MM-DDTHH:MM:SSZ, YYYY-MM-DDTHH:MM:SS\xB1HH:MM`
    );
  }
  const ms = Date.parse(raw);
  if (!Number.isFinite(ms)) {
    throw new Error(`--since is not a valid ISO 8601 timestamp: ${raw}`);
  }
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(raw);
  if (m) {
    const offsetMatch = /([+-])(\d{2}):?(\d{2})$/.exec(raw);
    let displayMs = ms;
    if (offsetMatch) {
      const sign = offsetMatch[1] === "-" ? -1 : 1;
      const offsetMin = sign * (Number(offsetMatch[2]) * 60 + Number(offsetMatch[3]));
      displayMs = ms + offsetMin * 6e4;
    }
    const dd = new Date(displayMs);
    if (dd.getUTCFullYear() !== Number(m[1]) || dd.getUTCMonth() + 1 !== Number(m[2]) || dd.getUTCDate() !== Number(m[3])) {
      throw new Error(
        `--since: calendar overflow \u2014 ${raw} normalises to a different calendar date`
      );
    }
  }
  return raw;
}
function parseCapsuleIncludeKinds(raw) {
  if (raw === void 0 || raw === null) return void 0;
  if (typeof raw !== "string") {
    throw new Error(
      `--include-kinds expects a comma-separated list of directory names; got ${JSON.stringify(raw)}`
    );
  }
  if (raw.trim() === "") {
    throw new Error(
      `--include-kinds expects at least one non-empty kind name`
    );
  }
  const parts = raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
  if (parts.length === 0) {
    throw new Error(`--include-kinds expects at least one non-empty kind name`);
  }
  for (const p of parts) {
    if (p.includes("/") || p.includes("\\")) {
      throw new Error(
        `--include-kinds entries must be top-level directory names (no path separators): ${p}`
      );
    }
  }
  return [...new Set(parts)];
}
function parseCapsulePeers(raw) {
  if (raw === void 0 || raw === null) return void 0;
  if (typeof raw !== "string") {
    throw new Error(
      `--peers expects a comma-separated list of peer ids; got ${JSON.stringify(raw)}`
    );
  }
  if (raw.trim() === "") {
    throw new Error(`--peers expects at least one non-empty peer id`);
  }
  const parts = raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
  if (parts.length === 0) {
    throw new Error(`--peers expects at least one non-empty peer id`);
  }
  for (const p of parts) {
    if (p.includes("/") || p.includes("\\") || p === "." || p === "..") {
      throw new Error(
        `--peers entries must be plain id tokens (no path separators): ${p}`
      );
    }
  }
  return [...new Set(parts)];
}
function parseCapsuleExportOptions(nameArg, opts) {
  if (typeof nameArg !== "string" || nameArg.trim() === "") {
    throw new Error(
      `capsule export: <name> is required (e.g. "remnic capsule export my-capsule")`
    );
  }
  const name = nameArg.trim();
  const out = typeof opts.out === "string" && opts.out.trim() !== "" ? opts.out.trim() : void 0;
  const since = parseCapsuleSince(opts.since);
  const includeKinds = parseCapsuleIncludeKinds(opts.includeKinds);
  const peers = parseCapsulePeers(opts.peers);
  return { name, out, since, includeKinds, peers };
}
function parseCapsuleImportOptions(archiveArg, opts) {
  if (typeof archiveArg !== "string" || archiveArg.trim() === "") {
    throw new Error(
      `capsule import: <archive> path is required (e.g. "remnic capsule import /path/to/my-capsule.capsule.json.gz")`
    );
  }
  const archive = archiveArg.trim();
  const mode = parseCapsuleImportMode(opts.mode);
  return { archive, mode };
}
function parseCapsuleMergeOptions(archiveArg, opts) {
  if (typeof archiveArg !== "string" || archiveArg.trim() === "") {
    throw new Error(
      `capsule merge: <archive> path is required (e.g. "remnic capsule merge /path/to/my-capsule.capsule.json.gz")`
    );
  }
  const archive = archiveArg.trim();
  const conflictMode = parseCapsuleConflictMode(opts.conflictMode);
  return { archive, conflictMode };
}
function parseCapsuleListOptions(opts, defaultCapsulesDir2) {
  const format = parseCapsuleOutputFormat(opts.format);
  const rawDir = typeof opts.dir === "string" && opts.dir.trim() !== "" ? opts.dir.trim() : void 0;
  const capsulesDir = rawDir ?? defaultCapsulesDir2;
  return { format, capsulesDir };
}
function parseCapsuleInspectOptions(archiveArg, opts) {
  if (typeof archiveArg !== "string" || archiveArg.trim() === "") {
    throw new Error(
      `capsule inspect: <archive> path is required (e.g. "remnic capsule inspect my-capsule.capsule.json.gz")`
    );
  }
  const archive = archiveArg.trim();
  const format = parseCapsuleOutputFormat(opts.format);
  return { archive, format };
}
function defaultCapsulesDir(memoryDir) {
  return path.join(memoryDir, ".capsules");
}
function escapeMarkdownCell(v) {
  return v.replace(/\\/g, "\\\\").replace(/\|/g, "\\|");
}
function renderCapsuleList(entries, format) {
  if (format === "json") {
    return JSON.stringify({ capsules: entries }, null, 2);
  }
  if (entries.length === 0) {
    if (format === "markdown") return "_No capsule archives found._\n";
    return "No capsule archives found.\n";
  }
  if (format === "markdown") {
    const rows = entries.map((e) => {
      const id = escapeMarkdownCell(e.id);
      const date = escapeMarkdownCell(e.createdAt?.slice(0, 10) ?? "\u2014");
      const ver = escapeMarkdownCell(e.pluginVersion ?? "\u2014");
      const files = e.fileCount !== null ? String(e.fileCount) : "\u2014";
      const desc = escapeMarkdownCell(
        e.description != null && e.description.trim() !== "" ? e.description.trim() : "\u2014"
      );
      return `| \`${id}\` | ${date} | ${ver} | ${files} | ${desc} |`;
    });
    return [
      "# Capsule archives",
      "",
      "| ID | Created | Version | Files | Description |",
      "| -- | ------- | ------- | ----- | ----------- |",
      ...rows,
      ""
    ].join("\n");
  }
  const lines = entries.map((e) => {
    const date = e.createdAt?.slice(0, 10) ?? "\u2014";
    const files = e.fileCount !== null ? `${e.fileCount} file${e.fileCount !== 1 ? "s" : ""}` : "? files";
    const desc = e.description != null && e.description.trim() !== "" ? `  ${e.description.trim()}` : "";
    return `${e.id}  [${date}] [${files}]${desc}`;
  });
  return lines.join("\n") + "\n";
}
function renderCapsuleInspect(manifest, format) {
  if (format === "json") {
    return JSON.stringify(manifest, null, 2);
  }
  const {
    capsuleId,
    version,
    schemaVersion,
    createdAt,
    pluginVersion,
    fileCount,
    includesTranscripts,
    description,
    parentCapsule,
    retrievalPolicy,
    includes,
    topFiles
  } = manifest;
  if (format === "markdown") {
    const policyLines = Object.entries(retrievalPolicy.tierWeights ?? {}).map(
      ([k, v]) => `  - ${k}: ${v}`
    );
    const policyBlock = policyLines.length > 0 ? policyLines.join("\n") : "  _(no tier weight overrides)_";
    return [
      `# Capsule: \`${capsuleId}\``,
      "",
      `**Version:** ${version}  `,
      `**Schema version:** ${schemaVersion}  `,
      `**Created:** ${createdAt ?? "\u2014"}  `,
      `**Plugin version:** ${pluginVersion ?? "\u2014"}  `,
      `**Files:** ${fileCount}  `,
      `**Includes transcripts:** ${includesTranscripts ? "yes" : "no"}  `,
      `**Parent capsule:** ${parentCapsule ?? "_none_"}  `,
      `**Description:** ${description && description.trim() !== "" ? description.trim() : "_none_"}  `,
      "",
      "## Includes",
      `- taxonomy: ${includes.taxonomy ? "yes" : "no"}`,
      `- identityAnchors: ${includes.identityAnchors ? "yes" : "no"}`,
      `- peerProfiles: ${includes.peerProfiles ? "yes" : "no"}`,
      `- procedural: ${includes.procedural ? "yes" : "no"}`,
      "",
      "## Retrieval policy",
      `- directAnswerEnabled: ${retrievalPolicy.directAnswerEnabled ? "yes" : "no"}`,
      `- tierWeights:`,
      policyBlock,
      "",
      ...topFiles.length > 0 ? [
        `## Files (${fileCount} total, showing first ${topFiles.length})`,
        ...topFiles.map((f) => `- \`${f}\``),
        ""
      ] : [`## Files (${fileCount} total)`, "_Empty capsule._", ""]
    ].join("\n");
  }
  const lines = [
    `Capsule: ${capsuleId}`,
    `  version:          ${version}`,
    `  schema:           ${schemaVersion}`,
    `  created:          ${createdAt ?? "\u2014"}`,
    `  plugin:           ${pluginVersion ?? "\u2014"}`,
    `  files:            ${fileCount}`,
    `  transcripts:      ${includesTranscripts ? "yes" : "no"}`,
    `  parent:           ${parentCapsule ?? "(none)"}`,
    `  description:      ${description && description.trim() !== "" ? description.trim() : "(none)"}`,
    "",
    `  includes.taxonomy:        ${includes.taxonomy ? "yes" : "no"}`,
    `  includes.identityAnchors: ${includes.identityAnchors ? "yes" : "no"}`,
    `  includes.peerProfiles:    ${includes.peerProfiles ? "yes" : "no"}`,
    `  includes.procedural:      ${includes.procedural ? "yes" : "no"}`,
    "",
    `  policy.directAnswer:   ${retrievalPolicy.directAnswerEnabled ? "yes" : "no"}`
  ];
  const weights = Object.entries(retrievalPolicy.tierWeights ?? {});
  if (weights.length > 0) {
    for (const [k, v] of weights) {
      lines.push(`  policy.tierWeight[${k}]: ${v}`);
    }
  } else {
    lines.push(`  policy.tierWeights:    (none)`);
  }
  if (topFiles.length > 0) {
    lines.push("", `  files (first ${topFiles.length} of ${fileCount}):`);
    for (const f of topFiles) {
      lines.push(`    ${f}`);
    }
  }
  return lines.join("\n") + "\n";
}

export {
  parseCapsuleOutputFormat,
  parseCapsuleImportMode,
  parseCapsuleConflictMode,
  parseCapsuleSince,
  parseCapsuleIncludeKinds,
  parseCapsulePeers,
  parseCapsuleExportOptions,
  parseCapsuleImportOptions,
  parseCapsuleMergeOptions,
  parseCapsuleListOptions,
  parseCapsuleInspectOptions,
  defaultCapsulesDir,
  renderCapsuleList,
  renderCapsuleInspect
};
//# sourceMappingURL=chunk-74EMIVE4.js.map