// 会话 → Markdown 导出器
// 仅保留对话主干（用户输入 + 模型文字输出），附时间戳；思考过程以折叠块呈现。
// 工具调用 / 工具结果 / 模型切换 / 压缩等元信息不导出（与 HTML 导出不同，后者由 pi CLI 生成）。

import type {
  SessionHeader,
  AgentMessage,
  UserMessage,
  AssistantMessage,
  TextContent,
} from "./types";

export interface ExportModel {
  provider: string;
  modelId: string;
}

const USER_HEADING = "## 👤 用户";
const ASSISTANT_HEADING = "## 🤖 助手";

function pad2(n: number): string {
  return String(n).padStart(2, "0");
}

/** 毫秒时间戳 → 本地 HH:MM:SS；无效返回 null */
function formatTime(ts?: number): string | null {
  if (typeof ts !== "number" || !Number.isFinite(ts) || ts <= 0) return null;
  const d = new Date(ts);
  if (Number.isNaN(d.getTime())) return null;
  return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
}

/** ISO 字符串 → 本地 YYYY-MM-DD HH:MM:SS */
function formatDateTime(iso?: string): string {
  if (!iso) return "未知";
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return iso;
  return (
    `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ` +
    `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
  );
}

/** 取 user 消息的纯文本（string 或 text block 数组拼接） */
function userText(msg: UserMessage): string {
  const c = msg.content;
  if (typeof c === "string") return c;
  return c
    .filter((b): b is TextContent => b.type === "text")
    .map((b) => b.text)
    .join("\n");
}

/**
 * 将会话消息序列导出为 Markdown。
 *
 * 规则：
 * - 仅处理 role 为 user / assistant 的消息；跳过 toolResult / custom
 * - user：取纯文本，空文字（如仅含图片）整条跳过
 * - assistant：输出 text block；thinking block 以 <details> 折叠；toolCall / image 跳过
 * - 纯工具调用轮次（无文字、无思考）整条跳过，不留空标题
 * - 每条消息标题附 HH:MM:SS 时间戳（若存在）
 */
export function exportSessionToMarkdown(
  header: SessionHeader,
  messages: AgentMessage[],
  model: ExportModel | null
): string {
  const out: string[] = [];

  // —— 元信息头 ——
  out.push("# Pi 会话记录", "");
  out.push(`- **工作目录**：${header.cwd || "未知"}`);
  out.push(`- **创建时间**：${formatDateTime(header.timestamp)}`);
  if (model) {
    out.push(`- **模型**：${model.provider}/${model.modelId}`);
  }
  out.push("", "---", "");

  // —— 对话正文 ——
  let started = false;

  for (const msg of messages) {
    if (msg.role !== "user" && msg.role !== "assistant") continue;

    const time = formatTime(msg.timestamp);
    const timeSuffix = time ? ` · ${time}` : "";

    if (msg.role === "user") {
      const text = userText(msg).trim();
      if (!text) continue;
      if (started) out.push("---", "");
      started = true;
      out.push(`${USER_HEADING}${timeSuffix}`, "", text, "");
      continue;
    }

    // assistant
    const a = msg as AssistantMessage;
    const texts: string[] = [];
    const thinkings: string[] = [];
    for (const block of a.content) {
      if (block.type === "text" && block.text.trim()) {
        texts.push(block.text.trim());
      } else if (block.type === "thinking" && block.thinking.trim()) {
        thinkings.push(block.thinking.trim());
      }
    }
    // 纯工具调用（无文字、无思考）→ 跳过
    if (texts.length === 0 && thinkings.length === 0) continue;
    if (started) out.push("---", "");
    started = true;
    out.push(`${ASSISTANT_HEADING}${timeSuffix}`, "");
    for (const t of texts) out.push(t, "");
    for (const th of thinkings) {
      out.push("<details>", "<summary>💭 思考过程</summary>", "", th, "", "</details>", "");
    }
  }

  return `${out.join("\n").trimEnd()}\n`;
}
