/**
 * Migration Manager
 *
 * Handles versioned migrations for configuration and data:
 * - Schema migrations
 * - Config file migrations
 * - Data format migrations
 * - Migration history tracking
 * - Transaction support with automatic rollback
 * - File-level locking to prevent race conditions
 * - Comprehensive audit trail
 */
import { EventEmitter } from 'events';
export interface Migration {
    version: string;
    name: string;
    description?: string;
    up: (context: MigrationContext) => Promise<void>;
    down: (context: MigrationContext) => Promise<void>;
    appliedAt?: Date;
}
export interface MigrationContext {
    dataDir: string;
    configDir: string;
    logger: MigrationLogger;
    dryRun: boolean;
    /** Backup a file before modification for transaction rollback */
    backupFile?: (filePath: string) => Promise<void>;
}
export interface MigrationLogger {
    info: (message: string) => void;
    warn: (message: string) => void;
    error: (message: string) => void;
    debug: (message: string) => void;
}
export interface MigrationHistory {
    version: string;
    name: string;
    appliedAt: Date;
    status: 'success' | 'failed' | 'rolled_back';
    duration: number;
    error?: string;
    transactionId?: string;
    checksum?: string;
}
/**
 * Audit log entry for migration operations
 */
export interface MigrationAuditEntry {
    id: string;
    timestamp: Date;
    operation: 'migrate' | 'rollback' | 'lock_acquired' | 'lock_released' | 'state_backup' | 'state_restored';
    version?: string;
    migrationName?: string;
    status: 'started' | 'completed' | 'failed';
    details?: string;
    durationMs?: number;
    userId?: string;
    hostname?: string;
}
/**
 * State backup for transaction rollback
 */
export interface StateBackup {
    transactionId: string;
    timestamp: Date;
    files: Map<string, Buffer | null>;
    metadata: Record<string, unknown>;
}
export interface MigrationResult {
    success: boolean;
    migrationsApplied: number;
    currentVersion: string;
    errors: string[];
    duration: number;
}
export interface MigrationManagerConfig {
    dataDir?: string;
    configDir?: string;
    historyFile?: string;
    auditFile?: string;
    lockFile?: string;
    dryRun?: boolean;
    verbose?: boolean;
    lockTimeoutMs?: number;
    enableAuditLog?: boolean;
}
/**
 * Migration Manager class
 */
export declare class MigrationManager extends EventEmitter {
    private config;
    private migrations;
    private history;
    private auditLog;
    private initialized;
    private logger;
    private lockHandle;
    private currentTransaction;
    private readonly hostname;
    private signalHandlersInstalled;
    private readonly signalHandler;
    constructor(config?: MigrationManagerConfig);
    /**
     * Install signal handlers for graceful cleanup on unexpected termination
     */
    private installSignalHandlers;
    /**
     * Remove signal handlers
     */
    private removeSignalHandlers;
    /**
     * Emergency cleanup - synchronously release lock on crash
     */
    private emergencyCleanup;
    /**
     * Create default logger
     */
    private createLogger;
    /**
     * Acquire exclusive lock for migrations
     * Prevents race conditions when multiple processes try to migrate
     */
    private acquireLock;
    /**
     * Release the migration lock
     */
    private releaseLock;
    /**
     * Begin a transaction by creating a state backup
     */
    private beginTransaction;
    /**
     * Verify transaction integrity before commit
     * Ensures all backed up files can be accessed and haven't been corrupted
     */
    private verifyTransactionIntegrity;
    /**
     * Backup a file before modification (part of transaction)
     */
    backupFile(filePath: string): Promise<void>;
    /**
     * Commit the current transaction (cleanup backups)
     * Verifies integrity before finalizing
     */
    private commitTransaction;
    /**
     * Rollback the current transaction by restoring files
     */
    private rollbackTransaction;
    /**
     * Load audit log from disk
     */
    private loadAuditLog;
    /**
     * Write an audit entry
     */
    private writeAuditEntry;
    /**
     * Get audit log entries
     */
    getAuditLog(options?: {
        version?: string;
        operation?: MigrationAuditEntry['operation'];
        status?: MigrationAuditEntry['status'];
        since?: Date;
        limit?: number;
    }): MigrationAuditEntry[];
    /**
     * Calculate checksum for migration verification
     */
    private calculateMigrationChecksum;
    /**
     * Initialize migration manager
     */
    initialize(): Promise<void>;
    /**
     * Load migration history from disk
     */
    private loadHistory;
    /**
     * Save migration history to disk
     */
    private saveHistory;
    /**
     * Register a migration
     */
    registerMigration(migration: Migration): void;
    /**
     * Register multiple migrations
     */
    registerMigrations(migrations: Migration[]): void;
    /**
     * Get all registered migrations sorted by version
     */
    getMigrations(): Migration[];
    /**
     * Get pending migrations (not yet applied)
     */
    getPendingMigrations(): Migration[];
    /**
     * Get applied migrations
     */
    getAppliedMigrations(): MigrationHistory[];
    /**
     * Get current version (latest applied migration)
     */
    getCurrentVersion(): string;
    /**
     * Get latest available version
     */
    getLatestVersion(): string;
    /**
     * Check if migrations are pending
     */
    hasPendingMigrations(): boolean;
    /**
     * Run all pending migrations with transaction support and locking
     */
    migrate(): Promise<MigrationResult>;
    /**
     * Migrate to a specific version
     */
    migrateTo(targetVersion: string): Promise<MigrationResult>;
    /**
     * Rollback the last migration with transaction support and locking
     */
    rollback(): Promise<MigrationResult>;
    /**
     * Rollback to a specific version
     */
    rollbackTo(targetVersion: string): Promise<MigrationResult>;
    /**
     * Create transaction-aware migration context
     * Includes file backup capability for automatic rollback on failure
     */
    private createTransactionContext;
    /**
     * Get migration history
     */
    getHistory(): MigrationHistory[];
    /**
     * Clear migration history (use with caution)
     */
    clearHistory(): Promise<void>;
    /**
     * Get migration status
     */
    getStatus(): {
        currentVersion: string;
        latestVersion: string;
        pendingCount: number;
        appliedCount: number;
        hasPending: boolean;
    };
    /**
     * Check if initialized
     */
    isInitialized(): boolean;
    /**
     * Dispose resources and cleanup
     */
    dispose(): void;
}
/**
 * Get or create migration manager
 */
export declare function getMigrationManager(config?: MigrationManagerConfig): MigrationManager;
/**
 * Reset migration manager singleton
 */
export declare function resetMigrationManager(): void;
export default MigrationManager;
