import { defaultCodexDirReadable, defaultListCodexAutomations, defaultReadClaudeScheduleListing, defaultResolveIdentity, loadDefaultListClaudeAutomations, resolveDefaultCodexAutomationsDir, } from "./ui-automations-adapters.js";
/** Stable probe id consumed by `/api/status` and the Automations section. */
export const AUTOMATIONS_PROBE_ID = "automations";
const PROBE_TIMEOUT_MS = 8_000;
const IDENTITY_UNAVAILABLE = "identity-unavailable";
const SCHEDULER_UNAVAILABLE = "scheduler-unavailable";
const SCHEDULER_UNREADABLE = "scheduler-unreadable";
const SCHEDULER_UNAVAILABLE_MESSAGE = "No harness scheduler is configured (Codex automations directory absent and Claude /schedule listing unavailable)";
/**
 * Map scheduler observations onto the live-status tri-state contract.
 * @param input - Prefix, runtime label, and raw observations
 * @returns Probe value with only prefix-matching automations
 */
export function mapHarnessAutomations(input) {
    const automations = input.observations
        .filter(entry => entry.automationId.startsWith(input.prefix))
        .map((entry) => ({
        id: entry.automationId,
        cadence: typeof entry.observedCadence === "string" &&
            entry.observedCadence.trim().length > 0
            ? entry.observedCadence
            : null,
        runtime: input.runtime,
        status: typeof entry.status === "string" && entry.status.trim().length > 0
            ? entry.status
            : null,
        lastRunAt: typeof entry.lastRunAt === "string" &&
            entry.lastRunAt.trim().length > 0
            ? entry.lastRunAt
            : null,
    }))
        .sort((left, right) => left.id.localeCompare(right.id));
    return {
        state: "value",
        value: {
            prefix: input.prefix,
            runtime: input.runtime,
            automations,
        },
    };
}
/**
 * Map thrown identity errors to unknown.
 * @param error - Thrown value
 * @returns Unknown identity result
 */
function identityUnknown(error) {
    const message = error instanceof Error && error.message.trim().length > 0
        ? error.message
        : "Unable to resolve repo identity for automation naming";
    return { state: "unknown", reason: IDENTITY_UNAVAILABLE, message };
}
/**
 * Map scheduler read failures to unknown.
 * @param error - Thrown value
 * @returns Unknown scheduler result
 */
function schedulerUnreadable(error) {
    const message = error instanceof Error && error.message.trim().length > 0
        ? error.message
        : "Harness scheduler could not be read";
    return { state: "unknown", reason: SCHEDULER_UNREADABLE, message };
}
/**
 * Create the Automations live-status probe.
 * @param dependencies - Project root plus injectable scheduler seams
 * @returns Probe registered under {@link AUTOMATIONS_PROBE_ID}
 */
export function createAutomationsProbe(dependencies) {
    const resolveIdentity = dependencies.resolveIdentity ?? defaultResolveIdentity;
    const listCodex = dependencies.listCodexAutomations ?? defaultListCodexAutomations;
    const readClaudeListing = dependencies.readClaudeScheduleListing ?? defaultReadClaudeScheduleListing;
    const codexReadable = dependencies.codexAutomationsDirReadable ?? defaultCodexDirReadable;
    const automationsDir = dependencies.automationsDir ?? resolveDefaultCodexAutomationsDir();
    return {
        id: AUTOMATIONS_PROBE_ID,
        timeoutMs: PROBE_TIMEOUT_MS,
        run: async (signal) => {
            const base = {
                cwd: dependencies.cwd,
                signal,
                resolveIdentity,
                listCodex,
                readClaudeListing,
                codexReadable,
                automationsDir,
            };
            return runAutomationsProbe(dependencies.listClaudeAutomations === undefined
                ? base
                : {
                    ...base,
                    listClaudeAutomations: dependencies.listClaudeAutomations,
                });
        },
    };
}
/**
 * Execute one automations probe cycle.
 * @param input - Bound collaborators for this request
 * @returns Probe result
 */
async function runAutomationsProbe(input) {
    const identity = await input.resolveIdentity(input.cwd, input.signal).then(value => ({ ok: true, value }), error => ({ ok: false, error }));
    if (!identity.ok) {
        return identityUnknown(identity.error);
    }
    if (await input.codexReadable(input.automationsDir, input.signal)) {
        try {
            return mapHarnessAutomations({
                prefix: identity.value.automationPrefix,
                runtime: "codex",
                observations: await input.listCodex({
                    automationsDir: input.automationsDir,
                    automationPrefix: identity.value.automationPrefix,
                    signal: input.signal,
                }),
            });
        }
        catch (error) {
            return schedulerUnreadable(error);
        }
    }
    const listing = await input.readClaudeListing(input.signal).then(value => ({ ok: true, value }), error => ({ ok: false, error }));
    if (!listing.ok) {
        return schedulerUnreadable(listing.error);
    }
    if (listing.value === null || listing.value === undefined) {
        return {
            state: "unknown",
            reason: SCHEDULER_UNAVAILABLE,
            message: SCHEDULER_UNAVAILABLE_MESSAGE,
        };
    }
    try {
        const listClaude = input.listClaudeAutomations ?? (await loadDefaultListClaudeAutomations());
        return mapHarnessAutomations({
            prefix: identity.value.automationPrefix,
            runtime: "claude",
            observations: listClaude({
                scheduleListing: listing.value,
                automationPrefix: identity.value.automationPrefix,
            }),
        });
    }
    catch (error) {
        return schedulerUnreadable(error);
    }
}
//# sourceMappingURL=ui-automations.js.map