/**
 * 检查点管理器
 * 管理检查点的创建、回滚、清理等操作
 */

import * as path from 'path';
import { nanoid } from 'nanoid';
import { getCheckpointsDir } from '../constants/paths.js';
import { ShadowGit, createShadowGit } from './shadow-git.js';
import { CheckpointLock } from './lock.js';
import { CheckpointSafetyChecker } from './safety.js';
import { WorkspacePathValidator } from './path-validator.js';
import { CommitMessageGenerator } from './commit-message.js';
import { LFSPatternLoader } from './lfs.js';
import {
  RestoreMode,
  type CheckpointMetadata,
  type CheckpointConfig,
  type CheckpointTrigger,
  type RollbackOptions,
  type RollbackResult,
  type DiffInfo,
  type FileDiff,
  type CheckpointEvent,
  type CheckpointEventListener,
  type RollbackRecord,
  type UnrevertResult,
  type SafetyCheckResult,
} from './types.js';

/**
 * 检查点提交消息前缀
 */
const CHECKPOINT_PREFIX = 'checkpoint:';

/**
 * 检查点管理器
 */
export class CheckpointManager {
  private shadowGit: ShadowGit;
  private config: CheckpointConfig;
  private workDir: string;
  private checkpointsIndex: Map<string, CheckpointMetadata> = new Map();
  private initialized = false;
  private lastCheckpointTime = 0;
  private eventListeners: Set<CheckpointEventListener> = new Set();

  // 新增：增强功能组件
  private lock: CheckpointLock;
  private safetyChecker: CheckpointSafetyChecker;
  private pathValidator: WorkspacePathValidator;
  private commitMessageGenerator: CommitMessageGenerator;
  private lfsLoader: LFSPatternLoader;

  // 新增：Unrevert 支持
  private lastRollback: RollbackRecord | null = null;

  // 新增：会话跟踪
  private currentSessionId: string | null = null;
  private sessionCheckpoints: Map<string, string[]> = new Map();

  // 防止重复创建检查点的最小间隔 (毫秒)
  private static readonly MIN_CHECKPOINT_INTERVAL = 1000;

  constructor(workDir: string, config: Partial<CheckpointConfig> = {}) {
    this.workDir = path.resolve(workDir);
    this.config = {
      enabled: true,
      autoCheckpoint: {
        beforeWrite: true,
        beforeEdit: true,
        beforeDelete: true,
        beforeMove: true,
        beforeBash: false,
      },
      maxCheckpoints: 100,
      maxAge: 7 * 24 * 60 * 60 * 1000,
      storageDir: getCheckpointsDir(),
      ...config,
    };

    this.shadowGit = createShadowGit(this.workDir, this.config.storageDir);

    // 初始化增强组件
    this.lock = new CheckpointLock(this.shadowGit.getShadowGitDir());
    this.safetyChecker = new CheckpointSafetyChecker(this.workDir);
    this.pathValidator = new WorkspacePathValidator();
    this.commitMessageGenerator = new CommitMessageGenerator();
    this.lfsLoader = new LFSPatternLoader();
  }

  /**
   * 初始化检查点管理器
   */
  async initialize(): Promise<void> {
    if (this.initialized) return;

    if (!this.config.enabled) {
      this.initialized = true;
      return;
    }

    // 验证工作目录路径
    const pathValidation = this.pathValidator.validate(this.workDir);
    if (!pathValidation.valid) {
      throw new Error(`Invalid workspace path: ${pathValidation.reason}`);
    }

    // 加载 LFS 模式
    await this.lfsLoader.loadPatterns(this.workDir);

    // 初始化 Shadow Git
    await this.shadowGit.initialize();

    // 加载检查点索引
    await this.loadCheckpointsIndex();

    this.initialized = true;
  }

  /**
   * 加载检查点索引
   */
  private async loadCheckpointsIndex(): Promise<void> {
    try {
      const commits = await this.shadowGit.getCommits(this.config.maxCheckpoints);

      for (const commit of commits) {
        if (commit.message.startsWith(CHECKPOINT_PREFIX)) {
          try {
            const jsonStr = commit.message.slice(CHECKPOINT_PREFIX.length);
            const metadata = JSON.parse(jsonStr) as CheckpointMetadata;
            metadata.commitHash = commit.hash;
            this.checkpointsIndex.set(metadata.id, metadata);
          } catch {
            // 解析失败，跳过
          }
        }
      }
    } catch {
      // 仓库可能是空的
    }
  }

  /**
   * 判断是否应该为指定工具创建检查点
   */
  shouldCreateCheckpoint(tool: string): boolean {
    if (!this.config.enabled) return false;

    const { autoCheckpoint } = this.config;

    switch (tool) {
      case 'write_file':
        return autoCheckpoint.beforeWrite;
      case 'edit_file':
        return autoCheckpoint.beforeEdit;
      case 'delete_file':
        return autoCheckpoint.beforeDelete;
      case 'move_file':
      case 'copy_file':
        return autoCheckpoint.beforeMove;
      case 'bash':
        return autoCheckpoint.beforeBash;
      default:
        return false;
    }
  }

  /**
   * 在工具执行前创建检查点
   */
  async beforeToolExecution(
    tool: string,
    params: Record<string, unknown>
  ): Promise<string | null> {
    if (!this.shouldCreateCheckpoint(tool)) {
      return null;
    }

    // 防止过于频繁的检查点创建
    const now = Date.now();
    if (now - this.lastCheckpointTime < CheckpointManager.MIN_CHECKPOINT_INTERVAL) {
      return null;
    }

    try {
      const checkpoint = await this.createCheckpoint({
        trigger: `tool:${tool}` as CheckpointTrigger,
        toolCall: { tool, params },
        description: this.generateDescription(tool, params),
      });

      this.lastCheckpointTime = now;
      return checkpoint.id;
    } catch (error) {
      console.warn('Failed to create checkpoint:', error);
      return null;
    }
  }

  /**
   * 生成检查点描述
   */
  private generateDescription(
    tool: string,
    params: Record<string, unknown>
  ): string {
    switch (tool) {
      case 'write_file':
        return `Write file: ${params.file_path || params.path}`;
      case 'edit_file':
        return `Edit file: ${params.file_path || params.path}`;
      case 'delete_file':
        return `Delete file: ${params.file_path || params.path}`;
      case 'move_file':
        return `Move: ${params.source} -> ${params.destination}`;
      case 'copy_file':
        return `Copy: ${params.source} -> ${params.destination}`;
      case 'bash':
        return `Bash: ${String(params.command).slice(0, 50)}`;
      default:
        return `Tool: ${tool}`;
    }
  }

  /**
   * 创建检查点
   */
  async createCheckpoint(options: {
    name?: string;
    description?: string;
    trigger?: CheckpointTrigger;
    toolCall?: { tool: string; params: Record<string, unknown> };
    messageId?: string;
    sessionId?: string;
    turnIndex?: number;
  }): Promise<CheckpointMetadata> {
    await this.initialize();

    if (!this.config.enabled) {
      throw new Error('Checkpoint system is disabled');
    }

    // 使用锁保护检查点创建
    return this.lock.withLock(async () => {
      const id = nanoid(10);
      const timestamp = Date.now();
      const trigger = options.trigger || 'manual';

      // 创建元数据
      const metadata: CheckpointMetadata = {
        id,
        name: options.name,
        description: options.description,
        timestamp,
        trigger,
        toolCall: options.toolCall,
        commitHash: '', // 待填充
        filesChanged: 0, // 待填充
        // 新增：消息和会话关联
        messageId: options.messageId,
        sessionId: options.sessionId || this.currentSessionId || undefined,
        turnIndex: options.turnIndex,
      };

      // 获取变更文件数
      let filesChanged: Array<{ path: string; type: string }> = [];
      try {
        const diff = await this.shadowGit.getWorkingDirDiff();
        metadata.filesChanged = diff.files.length;
        filesChanged = diff.files;
      } catch {
        // 忽略
      }

      // 生成智能提交消息
      const humanReadableMessage = this.commitMessageGenerator.generateMessage(
        trigger,
        options.toolCall,
        filesChanged as any
      );

      // 创建 commit（使用 JSON 元数据作为 commit message，但包含可读描述）
      const commitMessage = CHECKPOINT_PREFIX + JSON.stringify({
        ...metadata,
        _readableMessage: humanReadableMessage,
      });
      const commitHash = await this.shadowGit.createCommit(commitMessage);
      metadata.commitHash = commitHash;

      // 更新索引
      this.checkpointsIndex.set(id, metadata);

      // 记录到当前会话
      if (this.currentSessionId) {
        const sessionCps = this.sessionCheckpoints.get(this.currentSessionId) || [];
        sessionCps.push(id);
        this.sessionCheckpoints.set(this.currentSessionId, sessionCps);
      }

      // 触发事件
      this.emitEvent({
        type: 'created',
        checkpoint: metadata,
        timestamp,
      });

      // 异步清理
      this.cleanupAsync();

      return metadata;
    });
  }

  /**
   * 创建命名检查点
   */
  async createNamedCheckpoint(name: string, description?: string): Promise<CheckpointMetadata> {
    return this.createCheckpoint({
      name,
      description,
      trigger: 'manual',
    });
  }

  /**
   * 获取所有检查点
   */
  async listCheckpoints(): Promise<CheckpointMetadata[]> {
    await this.initialize();

    return Array.from(this.checkpointsIndex.values()).sort(
      (a, b) => b.timestamp - a.timestamp
    );
  }

  /**
   * 获取指定检查点
   */
  async getCheckpoint(idOrHash: string): Promise<CheckpointMetadata | null> {
    await this.initialize();

    // 先按 ID 查找
    if (this.checkpointsIndex.has(idOrHash)) {
      return this.checkpointsIndex.get(idOrHash)!;
    }

    // 再按 commit hash 查找
    for (const checkpoint of this.checkpointsIndex.values()) {
      if (checkpoint.commitHash.startsWith(idOrHash)) {
        return checkpoint;
      }
    }

    return null;
  }

  /**
   * 获取最近的检查点
   */
  async getLatestCheckpoint(): Promise<CheckpointMetadata | null> {
    const checkpoints = await this.listCheckpoints();
    return checkpoints[0] || null;
  }

  /**
   * 获取检查点与当前工作区的差异
   */
  async getDiff(checkpointId: string): Promise<DiffInfo> {
    await this.initialize();

    const checkpoint = await this.getCheckpoint(checkpointId);
    if (!checkpoint) {
      throw new Error(`Checkpoint not found: ${checkpointId}`);
    }

    return this.shadowGit.getDiffSummary(checkpoint.commitHash, 'HEAD');
  }

  /**
   * 获取两个检查点之间的差异
   */
  async getDiffBetween(fromId: string, toId: string): Promise<DiffInfo> {
    await this.initialize();

    const fromCheckpoint = await this.getCheckpoint(fromId);
    const toCheckpoint = await this.getCheckpoint(toId);

    if (!fromCheckpoint) {
      throw new Error(`Checkpoint not found: ${fromId}`);
    }
    if (!toCheckpoint) {
      throw new Error(`Checkpoint not found: ${toId}`);
    }

    return this.shadowGit.getDiffSummary(
      fromCheckpoint.commitHash,
      toCheckpoint.commitHash
    );
  }

  /**
   * 获取文件差异详情
   */
  async getFileDiff(checkpointId: string, filePath: string): Promise<FileDiff> {
    await this.initialize();

    const checkpoint = await this.getCheckpoint(checkpointId);
    if (!checkpoint) {
      throw new Error(`Checkpoint not found: ${checkpointId}`);
    }

    const head = await this.shadowGit.getHead();
    return this.shadowGit.getFileDiff(checkpoint.commitHash, head, filePath);
  }

  /**
   * 回滚到检查点
   */
  async rollback(options: RollbackOptions): Promise<RollbackResult> {
    await this.initialize();

    const checkpoint = await this.getCheckpoint(options.target);
    if (!checkpoint) {
      throw new Error(`Checkpoint not found: ${options.target}`);
    }

    // 安全检查（除非明确跳过）
    if (!options.skipSafetyCheck) {
      const safetyResult = await this.safetyChecker.checkBeforeRollback(checkpoint, this);
      if (!safetyResult.safe) {
        const errorMsg = safetyResult.errors.join('; ');
        throw new Error(`Safety check failed: ${errorMsg}`);
      }
      // 警告仍然记录，但不阻止操作
      if (safetyResult.warnings.length > 0) {
        console.warn('Rollback warnings:', safetyResult.warnings.join('; '));
      }
    }

    // 使用锁保护回滚操作
    return this.lock.withLock(async () => {
      // 获取当前 HEAD 用于可能的撤销
      const previousCommit = await this.shadowGit.getHead();

      // 预览模式
      if (options.dryRun) {
        const diff = await this.getDiff(checkpoint.id);
        return {
          success: true,
          restoredFiles: diff.files.map((f) => f.path),
          errors: [],
          previousCommit,
        };
      }

      // 创建回滚前检查点（用于 unrevert）
      let preRollbackCheckpoint: CheckpointMetadata | null = null;
      try {
        preRollbackCheckpoint = await this.createCheckpointInternal({
          trigger: 'pre_rollback',
          description: `Before rollback to ${options.target}`,
        });
      } catch {
        // 忽略创建失败
      }

      const result: RollbackResult = {
        success: true,
        restoredFiles: [],
        errors: [],
        previousCommit,
      };

      try {
        const mode = options.mode || RestoreMode.FULL;

        if (options.files && options.files.length > 0) {
          // 选择性回滚（指定文件）
          await this.shadowGit.checkoutFiles(checkpoint.commitHash, options.files);
          result.restoredFiles = options.files;
        } else if (mode === RestoreMode.AI_CHANGES_ONLY) {
          // 仅恢复 AI 修改的文件
          const aiFiles = await this.getAiModifiedFiles(checkpoint);
          if (aiFiles.length > 0) {
            await this.shadowGit.checkoutFiles(checkpoint.commitHash, aiFiles);
            result.restoredFiles = aiFiles;
          }
        } else if (mode === RestoreMode.WORKSPACE_ONLY) {
          // 仅恢复工作区变更（不包括 AI 修改）
          const workspaceFiles = await this.getWorkspaceOnlyFiles(checkpoint);
          if (workspaceFiles.length > 0) {
            await this.shadowGit.checkoutFiles(checkpoint.commitHash, workspaceFiles);
            result.restoredFiles = workspaceFiles;
          }
        } else {
          // 完整回滚
          await this.shadowGit.resetHard(checkpoint.commitHash);

          // 获取恢复的文件列表
          const diff = await this.shadowGit.getDiffSummary(
            previousCommit,
            checkpoint.commitHash
          );
          result.restoredFiles = diff.files.map((f) => f.path);
        }

        // 记录回滚信息（用于 unrevert）
        this.lastRollback = {
          id: nanoid(10),
          timestamp: Date.now(),
          targetCheckpoint: checkpoint.id,
          previousCommit: preRollbackCheckpoint?.commitHash || previousCommit,
          restoredFiles: result.restoredFiles,
          canUnrevert: true,
        };

        // 触发事件
        this.emitEvent({
          type: 'restored',
          checkpoint,
          timestamp: Date.now(),
          details: {
            files: result.restoredFiles,
            previousCommit,
            mode,
          },
        });
      } catch (error) {
        result.success = false;
        result.errors.push({
          file: '*',
          error: error instanceof Error ? error.message : String(error),
        });
      }

      return result;
    });
  }

  /**
   * 撤销最近一次回滚（Unrevert）
   */
  async unrevert(): Promise<UnrevertResult> {
    await this.initialize();

    if (!this.lastRollback || !this.lastRollback.canUnrevert) {
      return {
        success: false,
        restoredCommit: '',
        filesRestored: 0,
        error: 'No rollback to unrevert',
      };
    }

    return this.lock.withLock(async () => {
      try {
        // 恢复到回滚前的状态
        await this.shadowGit.resetHard(this.lastRollback!.previousCommit);

        const result: UnrevertResult = {
          success: true,
          restoredCommit: this.lastRollback!.previousCommit,
          filesRestored: this.lastRollback!.restoredFiles.length,
        };

        // 清除 unrevert 记录
        this.lastRollback = null;

        return result;
      } catch (error) {
        return {
          success: false,
          restoredCommit: '',
          filesRestored: 0,
          error: error instanceof Error ? error.message : String(error),
        };
      }
    });
  }

  /**
   * 检查是否可以执行 unrevert
   */
  canUnrevert(): boolean {
    return this.lastRollback !== null && this.lastRollback.canUnrevert;
  }

  /**
   * 获取最后一次回滚记录
   */
  getLastRollback(): RollbackRecord | null {
    return this.lastRollback;
  }

  /**
   * 执行安全检查
   */
  async checkSafety(checkpointId: string): Promise<SafetyCheckResult> {
    await this.initialize();

    const checkpoint = await this.getCheckpoint(checkpointId);
    if (!checkpoint) {
      return {
        safe: false,
        warnings: [],
        errors: ['Checkpoint not found'],
      };
    }

    return this.safetyChecker.checkBeforeRollback(checkpoint, this);
  }

  /**
   * 内部创建检查点（不使用锁，供 rollback 内部调用）
   */
  private async createCheckpointInternal(options: {
    trigger: CheckpointTrigger;
    description?: string;
  }): Promise<CheckpointMetadata> {
    const id = nanoid(10);
    const timestamp = Date.now();

    const metadata: CheckpointMetadata = {
      id,
      description: options.description,
      timestamp,
      trigger: options.trigger,
      commitHash: '',
      filesChanged: 0,
    };

    const commitMessage = CHECKPOINT_PREFIX + JSON.stringify(metadata);
    const commitHash = await this.shadowGit.createCommit(commitMessage);
    metadata.commitHash = commitHash;

    this.checkpointsIndex.set(id, metadata);

    return metadata;
  }

  /**
   * 获取 AI 修改的文件列表
   */
  private async getAiModifiedFiles(checkpoint: CheckpointMetadata): Promise<string[]> {
    const files: string[] = [];
    const checkpoints = await this.listCheckpoints();

    // 找到该检查点之后的所有检查点
    for (const cp of checkpoints) {
      if (cp.timestamp > checkpoint.timestamp && cp.toolCall) {
        const filePath =
          (cp.toolCall.params.file_path as string) ||
          (cp.toolCall.params.path as string);
        if (filePath && !files.includes(filePath)) {
          files.push(filePath);
        }
      }
    }

    return files;
  }

  /**
   * 获取仅工作区变更的文件（不包括 AI 修改）
   */
  private async getWorkspaceOnlyFiles(checkpoint: CheckpointMetadata): Promise<string[]> {
    const diff = await this.getDiff(checkpoint.id);
    const aiFiles = await this.getAiModifiedFiles(checkpoint);

    // 返回不在 AI 修改列表中的文件
    return diff.files
      .map((f) => f.path)
      .filter((path) => !aiFiles.includes(path));
  }

  /**
   * 撤销操作 (回滚到上一个检查点)
   */
  async undo(): Promise<RollbackResult> {
    const latest = await this.getLatestCheckpoint();
    if (!latest) {
      throw new Error('No checkpoints available');
    }

    // 找到倒数第二个检查点
    const checkpoints = await this.listCheckpoints();
    if (checkpoints.length < 2) {
      // 只有一个检查点，回滚到它
      return this.rollback({ target: latest.id });
    }

    // 回滚到倒数第二个检查点
    return this.rollback({ target: checkpoints[1].id });
  }

  /**
   * 删除检查点
   */
  async deleteCheckpoint(checkpointId: string): Promise<boolean> {
    await this.initialize();

    if (!this.checkpointsIndex.has(checkpointId)) {
      return false;
    }

    const checkpoint = this.checkpointsIndex.get(checkpointId)!;
    this.checkpointsIndex.delete(checkpointId);

    // 触发事件
    this.emitEvent({
      type: 'deleted',
      checkpoint,
      timestamp: Date.now(),
    });

    return true;
  }

  /**
   * 异步清理过期检查点
   */
  private async cleanupAsync(): Promise<void> {
    setTimeout(async () => {
      try {
        await this.cleanup();
      } catch (error) {
        console.warn('Checkpoint cleanup failed:', error);
      }
    }, 100);
  }

  /**
   * 清理过期检查点
   */
  async cleanup(): Promise<number> {
    await this.initialize();

    const checkpoints = await this.listCheckpoints();
    const now = Date.now();
    let deletedCount = 0;

    // 按时间过期清理
    for (const checkpoint of checkpoints) {
      if (now - checkpoint.timestamp > this.config.maxAge) {
        await this.deleteCheckpoint(checkpoint.id);
        deletedCount++;
      }
    }

    // 按数量限制清理
    const remaining = checkpoints.length - deletedCount;
    if (remaining > this.config.maxCheckpoints) {
      const toDelete = checkpoints.slice(this.config.maxCheckpoints);
      for (const checkpoint of toDelete) {
        if (this.checkpointsIndex.has(checkpoint.id)) {
          await this.deleteCheckpoint(checkpoint.id);
          deletedCount++;
        }
      }
    }

    if (deletedCount > 0) {
      // 触发清理事件
      this.emitEvent({
        type: 'cleanup',
        timestamp: now,
        details: { deletedCount },
      });

      // 运行 git gc
      await this.shadowGit.cleanup(this.config.maxCheckpoints);
    }

    return deletedCount;
  }

  /**
   * 获取检查点存储统计
   */
  async getStats(): Promise<{
    count: number;
    oldestTimestamp: number | null;
    newestTimestamp: number | null;
  }> {
    const checkpoints = await this.listCheckpoints();

    return {
      count: checkpoints.length,
      oldestTimestamp: checkpoints.length > 0
        ? checkpoints[checkpoints.length - 1].timestamp
        : null,
      newestTimestamp: checkpoints.length > 0 ? checkpoints[0].timestamp : null,
    };
  }

  /**
   * 添加事件监听器
   */
  addEventListener(listener: CheckpointEventListener): void {
    this.eventListeners.add(listener);
  }

  /**
   * 移除事件监听器
   */
  removeEventListener(listener: CheckpointEventListener): void {
    this.eventListeners.delete(listener);
  }

  /**
   * 触发事件
   */
  private emitEvent(event: CheckpointEvent): void {
    for (const listener of this.eventListeners) {
      try {
        listener(event);
      } catch (error) {
        console.warn('Checkpoint event listener error:', error);
      }
    }
  }

  /**
   * 检查是否启用
   */
  isEnabled(): boolean {
    return this.config.enabled;
  }

  /**
   * 获取配置
   */
  getConfig(): CheckpointConfig {
    return { ...this.config };
  }

  // ==================== 会话管理方法 ====================

  /**
   * 开始新会话
   */
  async startSession(sessionId?: string): Promise<string> {
    await this.initialize();

    const id = sessionId || nanoid(10);
    this.currentSessionId = id;
    this.sessionCheckpoints.set(id, []);

    // 创建会话开始检查点
    try {
      await this.createCheckpoint({
        trigger: 'session_start',
        description: `Session started: ${id}`,
        sessionId: id,
      });
    } catch {
      // 忽略创建失败
    }

    return id;
  }

  /**
   * 结束当前会话
   */
  async endSession(): Promise<void> {
    if (!this.currentSessionId) return;

    // 创建会话结束检查点
    try {
      await this.createCheckpoint({
        trigger: 'session_end',
        description: `Session ended: ${this.currentSessionId}`,
        sessionId: this.currentSessionId,
      });
    } catch {
      // 忽略创建失败
    }

    this.currentSessionId = null;
  }

  /**
   * 获取当前会话 ID
   */
  getCurrentSessionId(): string | null {
    return this.currentSessionId;
  }

  /**
   * 获取会话的所有检查点
   */
  async getSessionCheckpoints(sessionId: string): Promise<CheckpointMetadata[]> {
    await this.initialize();

    const checkpointIds = this.sessionCheckpoints.get(sessionId);
    if (!checkpointIds) return [];

    const checkpoints: CheckpointMetadata[] = [];
    for (const id of checkpointIds) {
      const checkpoint = this.checkpointsIndex.get(id);
      if (checkpoint) {
        checkpoints.push(checkpoint);
      }
    }

    return checkpoints.sort((a, b) => a.timestamp - b.timestamp);
  }

  /**
   * 创建与消息关联的检查点
   */
  async createMessageCheckpoint(
    messageId: string,
    turnIndex?: number,
    options?: {
      trigger?: CheckpointTrigger;
      description?: string;
    }
  ): Promise<CheckpointMetadata> {
    return this.createCheckpoint({
      trigger: options?.trigger || 'auto',
      description: options?.description || `Message checkpoint: ${messageId}`,
      messageId,
      sessionId: this.currentSessionId || undefined,
      turnIndex,
    });
  }

  /**
   * 获取与消息关联的检查点
   */
  async getMessageCheckpoints(messageId: string): Promise<CheckpointMetadata[]> {
    await this.initialize();

    const checkpoints: CheckpointMetadata[] = [];
    for (const checkpoint of this.checkpointsIndex.values()) {
      if (checkpoint.messageId === messageId) {
        checkpoints.push(checkpoint);
      }
    }

    return checkpoints.sort((a, b) => a.timestamp - b.timestamp);
  }

  /**
   * 撤销整个会话的修改
   */
  async undoSession(sessionId: string): Promise<RollbackResult> {
    const sessionCheckpoints = await this.getSessionCheckpoints(sessionId);
    if (sessionCheckpoints.length === 0) {
      throw new Error(`No checkpoints found for session: ${sessionId}`);
    }

    // 找到会话开始的检查点
    const startCheckpoint = sessionCheckpoints.find(
      (cp) => cp.trigger === 'session_start'
    );

    if (!startCheckpoint) {
      // 如果没有明确的开始检查点，使用第一个检查点
      return this.rollback({ target: sessionCheckpoints[0].id });
    }

    return this.rollback({ target: startCheckpoint.id });
  }

  /**
   * 获取 LFS 模式加载器
   */
  getLfsLoader(): LFSPatternLoader {
    return this.lfsLoader;
  }

  /**
   * 检查文件是否由 LFS 管理
   */
  isLfsFile(filePath: string): boolean {
    return this.lfsLoader.isLfsFile(filePath);
  }
}

// 全局检查点管理器实例
let globalCheckpointManager: CheckpointManager | null = null;

/**
 * 获取全局检查点管理器实例
 */
export function getCheckpointManager(): CheckpointManager {
  if (!globalCheckpointManager) {
    globalCheckpointManager = new CheckpointManager(process.cwd());
  }
  return globalCheckpointManager;
}

/**
 * 初始化全局检查点管理器
 */
export async function initCheckpointManager(
  workDir: string,
  config?: Partial<CheckpointConfig>
): Promise<CheckpointManager> {
  globalCheckpointManager = new CheckpointManager(workDir, config);
  await globalCheckpointManager.initialize();
  return globalCheckpointManager;
}

/**
 * 重置全局检查点管理器 (用于测试)
 */
export function resetCheckpointManager(): void {
  globalCheckpointManager = null;
}
