import * as plugins from './mod.plugins.js';
import { RollbackManager } from './classes.rollbackmanager.js';
import { ChangeCache } from './classes.changecache.js';
import { FormatStats } from './classes.formatstats.js';
import type { IFormatOperation, IFormatPlan } from './interfaces.format.js';

export class FormatContext {
  private rollbackManager: RollbackManager;
  private currentOperation: IFormatOperation | null = null;
  private changeCache: ChangeCache;
  private formatStats: FormatStats;
  
  constructor() {
    this.rollbackManager = new RollbackManager();
    this.changeCache = new ChangeCache();
    this.formatStats = new FormatStats();
  }
  
  async beginOperation(): Promise<void> {
    this.currentOperation = await this.rollbackManager.createOperation();
  }
  
  async trackFileChange(filepath: string): Promise<void> {
    if (!this.currentOperation) {
      throw new Error('No operation in progress. Call beginOperation() first.');
    }
    await this.rollbackManager.backupFile(filepath, this.currentOperation.id);
  }
  
  async commitOperation(): Promise<void> {
    if (!this.currentOperation) {
      throw new Error('No operation in progress. Call beginOperation() first.');
    }
    await this.rollbackManager.markComplete(this.currentOperation.id);
    this.currentOperation = null;
  }
  
  async rollbackOperation(): Promise<void> {
    if (!this.currentOperation) {
      throw new Error('No operation in progress. Call beginOperation() first.');
    }
    await this.rollbackManager.rollback(this.currentOperation.id);
    this.currentOperation = null;
  }
  
  async rollbackTo(operationId: string): Promise<void> {
    await this.rollbackManager.rollback(operationId);
  }
  
  getRollbackManager(): RollbackManager {
    return this.rollbackManager;
  }
  
  getChangeCache(): ChangeCache {
    return this.changeCache;
  }
  
  async initializeCache(): Promise<void> {
    await this.changeCache.initialize();
  }
  
  getFormatStats(): FormatStats {
    return this.formatStats;
  }
}