"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readRepoServiceState = readRepoServiceState;
exports.loadRepoServiceStateRegistry = loadRepoServiceStateRegistry;
exports.persistRepoServiceStateRegistry = persistRepoServiceStateRegistry;
exports.persistRepoServiceStateRegistrySafely = persistRepoServiceStateRegistrySafely;
const promises_1 = require("node:fs/promises");
const node_path_1 = __importDefault(require("node:path"));
const zod_1 = require("zod");
const file_readers_1 = require("./file-readers");
const service_repo_state_1 = require("./service-repo-state");
const paths_1 = require("./paths");
const repoCooldownStateSchema = zod_1.z.object({
    trackedProjectKey: zod_1.z.string().min(1),
    nextRetryAtMs: zod_1.z.number().int().nonnegative(),
    reason: zod_1.z.string().min(1),
    lastError: zod_1.z.string().min(1),
    updatedAt: zod_1.z.string().min(1),
});
const repoServiceStateSchema = zod_1.z.object({
    version: zod_1.z.literal(1),
    cooldowns: zod_1.z.array(repoCooldownStateSchema),
});
const EMPTY_STATE = {
    version: 1,
    cooldowns: [],
};
async function readRepoServiceState(homeDirectory) {
    const statePath = (0, paths_1.getServiceRepoStatePath)(homeDirectory);
    return (0, file_readers_1.readJsonFileOrDefault)(statePath, repoServiceStateSchema, () => ({
        ...EMPTY_STATE,
        cooldowns: [],
    }));
}
async function loadRepoServiceStateRegistry(homeDirectory) {
    const registry = (0, service_repo_state_1.createRepoServiceStateRegistry)();
    const nowMs = Date.now();
    const state = await readRepoServiceState(homeDirectory);
    for (const cooldown of state.cooldowns) {
        const { trackedProjectKey, ...cooldownState } = cooldown;
        if (cooldown.nextRetryAtMs > nowMs) {
            (0, service_repo_state_1.recordRepoCooldown)(registry, trackedProjectKey, cooldownState);
        }
    }
    return registry;
}
async function persistRepoServiceStateRegistry(registry, homeDirectory) {
    const statePath = (0, paths_1.getServiceRepoStatePath)(homeDirectory);
    await (0, promises_1.mkdir)(node_path_1.default.dirname(statePath), { recursive: true });
    const nowMs = Date.now();
    const cooldowns = [...registry.cooldownsByTrackedProjectKey.entries()]
        .filter(([, cooldown]) => cooldown.nextRetryAtMs > nowMs)
        .map(([trackedProjectKey, cooldown]) => ({
        trackedProjectKey,
        nextRetryAtMs: cooldown.nextRetryAtMs,
        reason: cooldown.reason,
        lastError: cooldown.lastError,
        updatedAt: cooldown.updatedAt,
    }));
    const normalized = repoServiceStateSchema.parse({
        version: 1,
        cooldowns,
    });
    await (0, promises_1.writeFile)(statePath, `${JSON.stringify(normalized, null, 2)}\n`, "utf8");
}
async function persistRepoServiceStateRegistrySafely(registry, homeDirectory) {
    try {
        await persistRepoServiceStateRegistry(registry, homeDirectory);
    }
    catch {
        // Best-effort persistence. The in-memory cooldown still protects the live run.
    }
}
