"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.RuntimeHealthMonitor = exports.RETRY_BUDGET_WINDOW_MS = exports.MAX_FAILURES = exports.MAX_DELAY_MS = exports.BASE_DELAY_MS = void 0;
exports.exponentialBackoffDelayMs = exponentialBackoffDelayMs;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("./util/AtomicWriter");
/**
 * Exponential backoff parameters.
 *
 *   delay = min(BASE_DELAY_MS * 2^(failures-1), MAX_DELAY_MS)
 *
 * After MAX_FAILURES failures within RETRY_BUDGET_WINDOW_MS the executor
 * is marked permanentlyDown until manual reset via markHealthy().
 *
 * Story 6.5 — OpenLife v1.2 Royal Stack.
 */
exports.BASE_DELAY_MS = 10_000; // 10s for first failure
exports.MAX_DELAY_MS = 60 * 60 * 1000; // 1h cap
exports.MAX_FAILURES = 10; // budget
exports.RETRY_BUDGET_WINDOW_MS = 60 * 60 * 1000; // 1h window
function exponentialBackoffDelayMs(failures) {
    if (failures <= 0)
        return exports.BASE_DELAY_MS;
    const exponent = Math.min(failures - 1, 30); // clamp to avoid 2^N overflow
    const delay = exports.BASE_DELAY_MS * Math.pow(2, exponent);
    return Math.min(delay, exports.MAX_DELAY_MS);
}
class RuntimeHealthMonitor {
    root;
    filePath;
    constructor(root = process.cwd()) {
        this.root = root;
        this.filePath = path.join(this.root, '.openlife', 'runtime-health.json');
        fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
    }
    read() {
        if (!fs.existsSync(this.filePath))
            return {};
        try {
            return JSON.parse(fs.readFileSync(this.filePath, 'utf-8'));
        }
        catch {
            return {};
        }
    }
    write(payload) {
        (0, AtomicWriter_1.writeJsonAtomic)(this.filePath, payload);
    }
    get(executor) {
        return this.read()[executor] || null;
    }
    isCoolingDown(executor) {
        const state = this.get(executor);
        if (!state)
            return false;
        if (state.permanentlyDown)
            return true;
        if (!state.until)
            return false;
        return new Date(state.until).getTime() > Date.now();
    }
    /**
     * Record an executor failure. The cooldown is computed via exponential
     * backoff unless `cooldownMinutes` is explicitly provided (backward-
     * compatible — pre-v1.2 callers passed a fixed 10-minute window).
     */
    markFailure(executor, reason, cooldownMinutes) {
        const current = this.read();
        const existing = current[executor];
        const now = Date.now();
        // Reset the failure window if more than RETRY_BUDGET_WINDOW_MS elapsed
        // since the window started — gives intermittent failures a clean slate.
        let failures = (existing?.failures || 0) + 1;
        let budgetWindowStartedAt = existing?.budgetWindowStartedAt;
        if (!budgetWindowStartedAt || now - budgetWindowStartedAt > exports.RETRY_BUDGET_WINDOW_MS) {
            budgetWindowStartedAt = now;
            failures = 1;
        }
        const permanentlyDown = failures > exports.MAX_FAILURES;
        const delayMs = cooldownMinutes !== undefined
            ? cooldownMinutes * 60 * 1000
            : exponentialBackoffDelayMs(failures);
        const until = permanentlyDown ? undefined : new Date(now + delayMs).toISOString();
        current[executor] = {
            executor,
            failures,
            until,
            reason,
            updatedAt: new Date().toISOString(),
            permanentlyDown,
            budgetWindowStartedAt,
        };
        this.write(current);
    }
    markHealthy(executor) {
        const current = this.read();
        current[executor] = {
            executor,
            failures: 0,
            updatedAt: new Date().toISOString(),
            permanentlyDown: false,
        };
        this.write(current);
    }
    all() {
        return this.read();
    }
}
exports.RuntimeHealthMonitor = RuntimeHealthMonitor;
