/**
 * Handler for `GET /api/mcp-status`.
 *
 * Returns a snapshot of the locally connected MCP servers managed by
 * `spectral serve`. Pure handler pattern — no framework, no side effects.
 * The caller (the relay dispatcher) injects `McpExtensionState`.
 *
 * This module intentionally imports ONLY `McpExtensionState` (a pure-type
 * import from `state.ts`). It avoids `init.ts` / `config.ts` / etc. so the
 * dispatcher never pulls in heavy transitive deps.
 */
/** Maximum age (ms) of a failure entry before we treat it as stale. */
const FAILURE_BACKOFF_MS = 60_000;
export function handleListMcpStatus(state) {
    const result = [];
    for (const name of Object.keys(state.config.mcpServers)) {
        const connection = state.manager.getConnection(name);
        const metadata = state.toolMetadata.get(name);
        const toolCount = metadata?.length ?? 0;
        const failedAgo = getFailureAgeSeconds(state, name);
        let status = "disconnected";
        let failedAt;
        if (connection?.status === "connected") {
            status = "connected";
        }
        else if (connection?.status === "needs-auth") {
            status = "needs-auth";
        }
        else if (failedAgo !== null) {
            status = "failed";
            failedAt = state.failureTracker.get(name) ?? undefined;
        }
        else if (metadata !== undefined) {
            status = "cached";
        }
        result.push({ name, status, toolCount, failedAt });
    }
    return result;
}
/**
 * Mirrors `init.ts#getFailureAgeSeconds` without pulling in init.ts's
 * heavy runtime deps (config, consent manager, UI resource handler, etc.).
 */
function getFailureAgeSeconds(state, serverName) {
    const failedAt = state.failureTracker.get(serverName);
    if (!failedAt)
        return null;
    const ageMs = Date.now() - failedAt;
    if (ageMs > FAILURE_BACKOFF_MS)
        return null;
    return Math.round(ageMs / 1000);
}
