// src/tools/file-checkpoint.ts
import { existsSync, readFileSync, writeFileSync, unlinkSync } from "fs";
var MAX_SNAPSHOTS = 200;
var FileCheckpointStore = class {
  snapshots = [];
  /**
   * 在文件写入前调用，保存当前文件内容。
   * 同一 messageIndex 下同一文件只记录首次快照。
   */
  snapshot(filePath, messageIndex) {
    const exists = this.snapshots.some(
      (s) => s.filePath === filePath && s.messageIndex === messageIndex
    );
    if (exists) return;
    let content = null;
    if (existsSync(filePath)) {
      try {
        content = readFileSync(filePath, "utf-8");
      } catch {
        return;
      }
    }
    this.snapshots.push({
      filePath,
      content,
      messageIndex,
      timestamp: Date.now()
    });
    if (this.snapshots.length > MAX_SNAPSHOTS) {
      this.snapshots = this.snapshots.slice(-MAX_SNAPSHOTS);
    }
  }
  /**
   * 恢复所有在指定消息索引之后被修改的文件到该索引时的状态。
   * @returns 恢复和删除的文件数量
   */
  restoreToMessageIndex(targetIndex) {
    const modifiedAfter = this.snapshots.filter((s) => s.messageIndex > targetIndex);
    const uniqueFiles = [...new Set(modifiedAfter.map((s) => s.filePath))];
    let restored = 0;
    let deleted = 0;
    const files = [];
    for (const filePath of uniqueFiles) {
      const beforeSnapshots = this.snapshots.filter((s) => s.filePath === filePath && s.messageIndex <= targetIndex).sort((a, b) => b.messageIndex - a.messageIndex);
      const restoreTo = beforeSnapshots[0];
      try {
        if (restoreTo) {
          if (restoreTo.content === null) {
            if (existsSync(filePath)) {
              unlinkSync(filePath);
              deleted++;
              files.push(filePath);
            }
          } else {
            writeFileSync(filePath, restoreTo.content, "utf-8");
            restored++;
            files.push(filePath);
          }
        } else {
          const earliest = this.snapshots.filter((s) => s.filePath === filePath).sort((a, b) => a.messageIndex - b.messageIndex)[0];
          if (earliest && earliest.content === null) {
            if (existsSync(filePath)) {
              unlinkSync(filePath);
              deleted++;
              files.push(filePath);
            }
          } else if (earliest) {
            writeFileSync(filePath, earliest.content, "utf-8");
            restored++;
            files.push(filePath);
          }
        }
      } catch {
      }
    }
    this.snapshots = this.snapshots.filter((s) => s.messageIndex <= targetIndex);
    return { restored, deleted, files };
  }
  /** 获取所有快照（供调试/显示） */
  getSnapshots() {
    return this.snapshots;
  }
  /** 获取有快照的消息索引列表（去重排序） */
  getMessageIndices() {
    return [...new Set(this.snapshots.map((s) => s.messageIndex))].sort((a, b) => a - b);
  }
  /** 清空所有快照（新会话/清除时调用） */
  clear() {
    this.snapshots = [];
  }
};
var fileCheckpoints = new FileCheckpointStore();

export {
  fileCheckpoints
};
