/**
 * olam memory status — diagnostic dump for the agent-memory Docker container.
 *
 * Phase B substrate: queries `MemoryServiceContainerController.status()` +
 * bearer-authenticated livez probe. Output schema preserves the Phase A
 * shape — `state | livez | secret | port` — but the `state` field now
 * reports container lifecycle (`running | stopped | missing`) instead of
 * pid/alive.
 *
 * Plan reference: docs/plans/memory-service-as-docker-peripheral/phase-b-tasks.md B3
 */
import { existsSync } from 'node:fs';
import { printInfo, printHeader, printWarning } from '../../output.js';
import { hasMemorySecret, readMemorySecretOrNull } from '../../lib/memory-secret.js';
import { MEMORY_LIVEZ_URL, MEMORY_REST_PORT, MEMORY_PID_PATH, } from './_paths.js';
import { MemoryServiceContainerController } from '../memory-service-container.js';
async function probe(secret) {
    try {
        const headers = {};
        if (secret)
            headers.authorization = `Bearer ${secret}`;
        const resp = await fetch(MEMORY_LIVEZ_URL, { headers });
        if (resp.status === 401)
            return 'unauthorized';
        if (!resp.ok)
            return 'unknown';
        const body = (await resp.json());
        return body.status === 'ok' ? 'ok' : 'unknown';
    }
    catch {
        return 'unreachable';
    }
}
export async function collectMemoryStatus() {
    const controller = new MemoryServiceContainerController();
    const containerStatus = controller.status();
    const secret = readMemorySecretOrNull();
    const livez = await probe(secret);
    return {
        state: containerStatus.state,
        containerId: containerStatus.containerId ?? null,
        livez,
        secretSet: hasMemorySecret(),
        port: MEMORY_REST_PORT,
        legacyPidfilePresent: existsSync(MEMORY_PID_PATH),
    };
}
export async function runMemoryStatus(opts = {}) {
    const s = await collectMemoryStatus();
    if (opts.json) {
        process.stdout.write(JSON.stringify(s, null, 2) + '\n');
        return s.livez === 'ok' ? 0 : 1;
    }
    printHeader('olam memory status');
    printInfo('state', s.state);
    if (s.containerId)
        printInfo('container', s.containerId.slice(0, 12));
    printInfo('livez', s.livez);
    printInfo('secret', s.secretSet ? '~/.olam/memory-secret (set)' : '(missing)');
    printInfo('port', `${s.port}`);
    if (s.legacyPidfilePresent) {
        printWarning('~/.olam/memory.pid is present (Phase A legacy artefact). ' +
            'Will be cleaned up on next `olam memory start` or `olam memory stop`.');
    }
    if (s.state === 'running' && s.livez === 'ok')
        return 0;
    if (s.state === 'missing') {
        printWarning('no olam-memory-service container exists; run `olam memory start`');
        return 1;
    }
    if (s.livez === 'unauthorized') {
        printWarning('livez returned 401 — the container is up but the local secret does not match. ' +
            'The container was likely started with a different secret. ' +
            '`olam memory stop && olam memory start` will reconcile.');
        return 1;
    }
    if (s.livez === 'unreachable' && s.state === 'running') {
        printWarning('container is running but /agentmemory/livez did not respond. ' +
            'Check `olam memory logs` for startup errors.');
        return 1;
    }
    if (!s.secretSet) {
        printWarning('secret missing; `olam memory start` will generate it');
    }
    return s.livez === 'ok' ? 0 : 1;
}
export function registerMemoryStatus(cmd) {
    cmd
        .command('status')
        .description('Diagnostic dump for the agent-memory Docker container (Phase B substrate).')
        .option('--json', 'Machine-readable JSON output', false)
        .action(async (opts) => {
        const rc = await runMemoryStatus(opts);
        if (rc !== 0)
            process.exitCode = rc;
    });
}
//# sourceMappingURL=status.js.map