"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var ExportWizard_exports = {};
__export(ExportWizard_exports, {
  default: () => ExportWizard_default
});
module.exports = __toCommonJS(ExportWizard_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_promises = __toESM(require("fs/promises"), 1);
var import_path = __toESM(require("path"), 1);
function generateDefaultFilename(sessionId, format) {
  const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
  const shortId = sessionId ? sessionId.slice(0, 6) : "unknown";
  const ext = format === "markdown" ? "md" : "json";
  return `conversation-${date}-${shortId}.${ext}`;
}
function formatAsMarkdown(messages, metadata, includeToolCalls) {
  const lines = [];
  lines.push("# Conversation Export");
  lines.push("");
  lines.push(`- **Session**: ${metadata.sessionId}`);
  if (metadata.title) {
    lines.push(`- **Title**: ${metadata.title}`);
  }
  if (metadata.createdAt) {
    lines.push(`- **Created**: ${metadata.createdAt}`);
  }
  lines.push(`- **Exported**: ${(/* @__PURE__ */ new Date()).toISOString()}`);
  lines.push("");
  lines.push("---");
  lines.push("");
  for (const msg of messages) {
    const role = msg.role.charAt(0).toUpperCase() + msg.role.slice(1);
    if (!includeToolCalls && msg.role === "tool") {
      continue;
    }
    lines.push(`## ${role}`);
    if (msg.timestamp) {
      lines.push(`*${msg.timestamp}*`);
    }
    lines.push("");
    if (typeof msg.content === "string") {
      lines.push(msg.content);
    } else if (Array.isArray(msg.content)) {
      for (const part of msg.content) {
        if (typeof part === "string") {
          lines.push(part);
        } else if (part && typeof part === "object") {
          if ("text" in part) {
            lines.push(String(part.text));
          } else if ("type" in part && part.type === "tool-call" && includeToolCalls) {
            const toolCall = part;
            lines.push("");
            lines.push(`### Tool: ${toolCall.toolName || "unknown"}`);
            lines.push("```json");
            lines.push(JSON.stringify(toolCall.args || {}, null, 2));
            lines.push("```");
          } else if ("type" in part && part.type === "tool-result" && includeToolCalls) {
            const toolResult = part;
            lines.push("");
            lines.push("<details>");
            lines.push(
              `<summary>Result: ${toolResult.toolName || "unknown"}</summary>`
            );
            lines.push("");
            lines.push("```");
            const resultStr = typeof toolResult.result === "string" ? toolResult.result : JSON.stringify(toolResult.result, null, 2);
            if (resultStr.length > 2e3) {
              lines.push(resultStr.slice(0, 2e3) + "\n... (truncated)");
            } else {
              lines.push(resultStr);
            }
            lines.push("```");
            lines.push("</details>");
          }
        }
      }
    } else if (msg.content && typeof msg.content === "object") {
      lines.push("```json");
      lines.push(JSON.stringify(msg.content, null, 2));
      lines.push("```");
    }
    lines.push("");
    lines.push("---");
    lines.push("");
  }
  return lines.join("\n");
}
function formatAsJson(messages, metadata, includeToolCalls) {
  const filteredMessages = includeToolCalls ? messages : messages.filter((m) => m.role !== "tool").map((m) => ({
    ...m,
    content: Array.isArray(m.content) ? m.content.filter((part) => {
      if (!part || typeof part !== "object") return true;
      return !("type" in part && (part.type === "tool-call" || part.type === "tool-result"));
    }) : m.content
  }));
  return JSON.stringify(
    {
      exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
      session: metadata,
      messages: filteredMessages
    },
    null,
    2
  );
}
const ExportWizard = (0, import_react.forwardRef)(function ExportWizard2({ isVisible, agent, sessionId, onClose }, ref) {
  const [step, setStep] = (0, import_react.useState)("format");
  const [options, setOptions] = (0, import_react.useState)({
    format: "markdown",
    includeToolCalls: true,
    filename: ""
  });
  const [selectedIndex, setSelectedIndex] = (0, import_react.useState)(0);
  const [filenameInput, setFilenameInput] = (0, import_react.useState)("");
  const [exportResult, setExportResult] = (0, import_react.useState)(null);
  (0, import_react.useEffect)(() => {
    if (isVisible) {
      setStep("format");
      setOptions({
        format: "markdown",
        includeToolCalls: true,
        filename: ""
      });
      setSelectedIndex(0);
      setFilenameInput("");
      setExportResult(null);
    }
  }, [isVisible]);
  (0, import_react.useEffect)(() => {
    if (step === "filename" && !filenameInput) {
      setFilenameInput(generateDefaultFilename(sessionId, options.format));
    }
  }, [step, sessionId, options.format, filenameInput]);
  const doExport = (0, import_react.useCallback)(async () => {
    if (!sessionId) {
      setExportResult({ success: false, error: "No active session" });
      setStep("error");
      return;
    }
    setStep("exporting");
    try {
      const history = await agent.getSessionHistory(sessionId);
      const metadata = await agent.getSessionMetadata(sessionId);
      const exportMetadata = {
        sessionId,
        title: metadata?.title,
        createdAt: metadata?.createdAt ? new Date(metadata.createdAt).toISOString() : void 0
      };
      const formattedHistory = history.map((msg) => ({
        role: msg.role,
        content: msg.content,
        timestamp: "timestamp" in msg && typeof msg.timestamp === "number" ? new Date(msg.timestamp).toISOString() : void 0
      }));
      const content = options.format === "markdown" ? formatAsMarkdown(formattedHistory, exportMetadata, options.includeToolCalls) : formatAsJson(formattedHistory, exportMetadata, options.includeToolCalls);
      const rawFilename = options.filename || filenameInput;
      const safeFilename = import_path.default.basename(rawFilename);
      const outputPath = import_path.default.resolve(process.cwd(), safeFilename);
      await import_promises.default.writeFile(outputPath, content, "utf-8");
      setExportResult({ success: true, path: outputPath });
      setStep("done");
    } catch (error) {
      setExportResult({
        success: false,
        error: error instanceof Error ? error.message : String(error)
      });
      setStep("error");
    }
  }, [agent, sessionId, options, filenameInput]);
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      handleInput: (input, key) => {
        if (!isVisible) return false;
        if (key.escape) {
          onClose();
          return true;
        }
        if (step === "done" || step === "error") {
          if (key.return || key.escape) {
            onClose();
          }
          return true;
        }
        if (step === "format") {
          if (key.upArrow || key.downArrow) {
            setSelectedIndex((prev) => prev === 0 ? 1 : 0);
            return true;
          }
          if (key.return) {
            setOptions((prev) => ({
              ...prev,
              format: selectedIndex === 0 ? "markdown" : "json"
            }));
            setSelectedIndex(0);
            setStep("toolCalls");
            return true;
          }
          return false;
        }
        if (step === "toolCalls") {
          if (key.upArrow || key.downArrow) {
            setSelectedIndex((prev) => prev === 0 ? 1 : 0);
            return true;
          }
          if (key.return) {
            setOptions((prev) => ({
              ...prev,
              includeToolCalls: selectedIndex === 0
            }));
            setFilenameInput(generateDefaultFilename(sessionId, options.format));
            setStep("filename");
            return true;
          }
          return false;
        }
        if (step === "filename") {
          if (key.return) {
            const finalFilename = filenameInput.trim();
            if (!finalFilename) {
              return true;
            }
            setOptions((prev) => ({ ...prev, filename: finalFilename }));
            setSelectedIndex(0);
            setStep("confirm");
            return true;
          }
          if (key.backspace || key.delete) {
            setFilenameInput((prev) => prev.slice(0, -1));
            return true;
          }
          if (input && !key.ctrl && !key.meta) {
            setFilenameInput((prev) => prev + input);
            return true;
          }
          return false;
        }
        if (step === "confirm") {
          if (key.upArrow || key.downArrow) {
            setSelectedIndex((prev) => prev === 0 ? 1 : 0);
            return true;
          }
          if (key.return) {
            if (selectedIndex === 0) {
              doExport();
            } else {
              onClose();
            }
            return true;
          }
          return false;
        }
        return false;
      }
    }),
    [isVisible, step, selectedIndex, options, filenameInput, onClose, doExport, sessionId]
  );
  if (!isVisible) return null;
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
    import_ink.Box,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: "cyan",
      paddingX: 1,
      marginTop: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: true, color: "cyan", children: "\u{1F4E4} Export Conversation" }) }),
        step === "format" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: "Select export format:" }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginTop: 1, flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { ...selectedIndex === 0 ? { color: "cyan" } : {}, children: [
              selectedIndex === 0 ? "\u276F " : "  ",
              "Markdown (.md) - Human readable"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { ...selectedIndex === 1 ? { color: "cyan" } : {}, children: [
              selectedIndex === 1 ? "\u276F " : "  ",
              "JSON (.json) - Structured data"
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2191\u2193 to select \u2022 Enter to continue \u2022 Esc to cancel" }) })
        ] }),
        step === "toolCalls" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: "Include tool calls and results?" }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginTop: 1, flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { ...selectedIndex === 0 ? { color: "cyan" } : {}, children: [
              selectedIndex === 0 ? "\u276F " : "  ",
              "Yes - Include all tool interactions"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { ...selectedIndex === 1 ? { color: "cyan" } : {}, children: [
              selectedIndex === 1 ? "\u276F " : "  ",
              "No - Only user and assistant messages"
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2191\u2193 to select \u2022 Enter to continue \u2022 Esc to cancel" }) })
        ] }),
        step === "filename" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: "Filename:" }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", children: "> " }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: filenameInput }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "cyan", children: "_" })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Enter to continue \u2022 Esc to cancel" }) })
        ] }),
        step === "confirm" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: "Export with these settings?" }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginTop: 1, flexDirection: "column", marginLeft: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
              "Format:",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "white", children: options.format === "markdown" ? "Markdown" : "JSON" })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
              "Tool calls:",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "white", children: options.includeToolCalls ? "Yes" : "No" })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
              "File: ",
              /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "white", children: filenameInput })
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginTop: 1, flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { ...selectedIndex === 0 ? { color: "green" } : {}, children: [
              selectedIndex === 0 ? "\u276F " : "  ",
              "Export"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { ...selectedIndex === 1 ? { color: "red" } : {}, children: [
              selectedIndex === 1 ? "\u276F " : "  ",
              "Cancel"
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2191\u2193 to select \u2022 Enter to confirm" }) })
        ] }),
        step === "exporting" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellow", children: "Exporting..." }) }),
        step === "done" && exportResult?.success && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "green", children: "\u2713 Exported successfully!" }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Saved to: " }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: exportResult.path })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Press Enter or Esc to close" }) })
        ] }),
        step === "error" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "red", children: "\u2717 Export failed" }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "red", children: exportResult?.error }) }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Press Enter or Esc to close" }) })
        ] })
      ]
    }
  );
});
var ExportWizard_default = ExportWizard;
