"use strict";
/**
 * AgentDiscovery — read `gateway-manifest.json` from any cwd and classify
 * daemon liveness based on `refreshedAt` staleness.
 *
 * v1.11.0 — Core ↔ Agent Bridge.
 *
 * Path precedence (matches v1.8.3 multi-root catalog resolution):
 *   1. `<OPENLIFE_STATE_DIR or <cwd>/.openlife>/gateway-manifest.json` — cwd-local
 *   2. `~/.openlife/gateway-manifest.json` — machine-scoped fallback
 *
 * Staleness thresholds mirror StatusCommand.ts:
 *   - fresh  (alive=true):  age <= 60s
 *   - stale  (alive=true):  60s < age <= 300s
 *   - dead   (alive=false): age > 300s
 *   - missing (alive=false): manifest file absent or unparseable
 */
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.HEARTBEAT_STALE_S = exports.HEARTBEAT_FRESH_S = void 0;
exports.discover = discover;
exports._candidatePaths = _candidatePaths;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const GatewayManifest_1 = require("../orchestrator/util/GatewayManifest");
exports.HEARTBEAT_FRESH_S = 60;
exports.HEARTBEAT_STALE_S = 300;
function candidatePaths() {
    const list = [];
    const cwdState = process.env.OPENLIFE_STATE_DIR || path.join(process.cwd(), '.openlife');
    const cwdFile = path.join(cwdState, GatewayManifest_1.MANIFEST_FILENAME);
    list.push({ src: 'cwd', file: cwdFile });
    const homeFile = path.join(os.homedir(), '.openlife', GatewayManifest_1.MANIFEST_FILENAME);
    if (homeFile !== cwdFile)
        list.push({ src: 'home', file: homeFile });
    return list;
}
function classify(ageSeconds) {
    if (ageSeconds == null)
        return 'missing';
    if (ageSeconds <= exports.HEARTBEAT_FRESH_S)
        return 'fresh';
    if (ageSeconds <= exports.HEARTBEAT_STALE_S)
        return 'stale';
    return 'dead';
}
function isWellFormed(raw) {
    if (!raw || typeof raw !== 'object')
        return false;
    const r = raw;
    return typeof r.port === 'number'
        && typeof r.token === 'string'
        && typeof r.host === 'string'
        && typeof r.pid === 'number'
        && typeof r.refreshedAt === 'string';
}
function discover() {
    for (const { src, file } of candidatePaths()) {
        if (!fs.existsSync(file))
            continue;
        let raw;
        try {
            raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
        }
        catch {
            continue;
        }
        if (!isWellFormed(raw))
            continue;
        const refreshedMs = Date.parse(raw.refreshedAt || raw.startedAt);
        const ageSeconds = Number.isFinite(refreshedMs)
            ? Math.max(0, Math.floor((Date.now() - refreshedMs) / 1000))
            : null;
        const liveness = classify(ageSeconds);
        return {
            alive: liveness === 'fresh' || liveness === 'stale',
            liveness,
            manifest: raw,
            ageSeconds,
            source: src,
            path: file,
        };
    }
    return { alive: false, liveness: 'missing', manifest: null, ageSeconds: null, source: null, path: null };
}
/** Exposed for tests so they can assert the discovery order. */
function _candidatePaths() {
    return candidatePaths();
}
