/**
 * Persistent Circuit Breaker
 *
 * Wraps the in-memory SyncCircuitBreaker with file-based persistence
 * so open/closed state survives across process restarts.
 *
 * State file format: { state, failures, lastFailure }
 */
import { readFileSync, writeFileSync, mkdirSync } from 'fs';
import { dirname } from 'path';
import { SyncCircuitBreaker } from '../increment/sync-circuit-breaker.js';
export class PersistentCircuitBreaker {
    constructor(filePath) {
        this.filePath = filePath;
        this.breaker = new SyncCircuitBreaker();
        this.loadState();
    }
    canSync() {
        return this.breaker.canSync();
    }
    recordSuccess() {
        this.breaker.recordSuccess();
        this.saveState();
    }
    recordFailure() {
        this.breaker.recordFailure();
        this.saveState();
    }
    reset() {
        this.breaker.reset();
        this.saveState();
    }
    getState() {
        return this.breaker.getState();
    }
    loadState() {
        try {
            const raw = readFileSync(this.filePath, 'utf-8');
            const data = JSON.parse(raw);
            // Replay persisted state onto the in-memory breaker
            for (let i = 0; i < (data.failures ?? 0); i++) {
                this.breaker.recordFailure();
            }
        }
        catch {
            // No file or corrupted — start fresh (closed)
        }
    }
    saveState() {
        const state = this.breaker.getState();
        const data = {
            state: state.state,
            failures: state.failures,
            lastFailure: state.lastFailure?.toISOString(),
        };
        try {
            mkdirSync(dirname(this.filePath), { recursive: true });
            writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf-8');
        }
        catch {
            // Best-effort persistence — don't crash on write failure
        }
    }
}
//# sourceMappingURL=persistent-circuit-breaker.js.map