function countRequests(requests) {
    return {
        requests,
        total: requests.length,
        pending: requests.filter((request) => request.status === 'pending').length,
        approved: requests.filter((request) => request.status === 'approved').length,
        verified: requests.filter((request) => request.status === 'verified').length,
        rejected: requests.filter((request) => request.status === 'rejected').length,
        expired: requests.filter((request) => request.status === 'expired').length,
    };
}
function collectPeerIds(peers, contracts, sessions, requests, work) {
    const ids = new Set();
    for (const peer of peers)
        ids.add(peer.id);
    for (const contract of contracts)
        ids.add(contract.runnerId);
    for (const session of sessions)
        ids.add(session.runnerId);
    for (const request of requests) {
        if (request.peerId)
            ids.add(request.peerId);
        if (request.requestedId)
            ids.add(request.requestedId);
    }
    for (const item of work)
        ids.add(item.peerId);
    return [...ids].sort();
}
function buildAcpSnapshot(store) {
    const state = store.getState().acp;
    return {
        transportState: state.managerTransportState,
        totalMessages: state.totalMessages,
        activeConnections: state.activeConnectionIds
            .map((id) => state.connections.get(id))
            .filter((connection) => connection !== undefined),
    };
}
function buildPeerSnapshot(deps, peerId) {
    deps.remoteRunnerRegistry.ensureContractsFromStore(deps.runtimeStore);
    const peers = deps.distributedRuntime.listPeers(undefined, 500);
    const peer = peers.find((entry) => entry.id === peerId) ?? null;
    const runnerContract = deps.remoteRunnerRegistry.getContract(peerId);
    const pairRequests = deps.distributedRuntime
        .listPairRequests(250)
        .filter((request) => request.peerId === peerId || request.requestedId === peerId);
    const pendingWork = deps.distributedRuntime.listWork(250, peerId);
    const artifacts = deps.remoteRunnerRegistry.listArtifacts().filter((artifact) => artifact.runnerId === peerId);
    const sessions = deps.remoteSupervisor.getSnapshot(deps.runtimeStore).sessions;
    const session = sessions.find((entry) => entry.runnerId === peerId) ?? null;
    if (!peer && !runnerContract && !session && pairRequests.length === 0 && pendingWork.length === 0 && artifacts.length === 0) {
        return null;
    }
    return {
        peerId,
        peer,
        session,
        runnerContract: runnerContract ?? null,
        pairRequests,
        pendingWork,
        artifacts,
    };
}
function buildPeerSnapshots(deps) {
    deps.remoteRunnerRegistry.ensureContractsFromStore(deps.runtimeStore);
    const pairingRequests = deps.distributedRuntime.listPairRequests(250);
    const peers = deps.distributedRuntime.listPeers(undefined, 500);
    const work = deps.distributedRuntime.listWork(500);
    const contracts = deps.remoteRunnerRegistry.listContracts();
    const sessions = deps.remoteSupervisor.getSnapshot(deps.runtimeStore).sessions;
    const peerIds = collectPeerIds(peers, contracts, sessions, pairingRequests, work);
    const snapshots = peerIds
        .map((peerId) => buildPeerSnapshot(deps, peerId))
        .filter((snapshot) => snapshot !== null);
    return Object.freeze(snapshots);
}
function buildSnapshot(deps) {
    deps.remoteRunnerRegistry.ensureContractsFromStore(deps.runtimeStore);
    const pairingRequests = deps.distributedRuntime.listPairRequests(250);
    const peers = deps.distributedRuntime.listPeers(undefined, 500);
    const work = deps.distributedRuntime.listWork(500);
    const pools = deps.remoteRunnerRegistry.listPools();
    const contracts = deps.remoteRunnerRegistry.listContracts();
    const artifacts = deps.remoteRunnerRegistry.listArtifacts();
    const supervisor = deps.remoteSupervisor.getSnapshot(deps.runtimeStore);
    return Object.freeze({
        capturedAt: Date.now(),
        nodeHostContract: deps.distributedRuntime.getNodeHostContract(),
        acp: buildAcpSnapshot(deps.runtimeStore),
        pairing: countRequests(pairingRequests),
        peers,
        peerSnapshots: buildPeerSnapshots(deps),
        work,
        runners: {
            pools,
            contracts,
            artifacts,
        },
        supervisor,
    });
}
export function createPeerClient(deps) {
    const resolved = Object.freeze({ ...deps });
    return {
        pairing: {
            listRequests(limit = 100) {
                return resolved.distributedRuntime.listPairRequests(limit);
            },
            request(input) {
                return resolved.distributedRuntime.requestPairing(input);
            },
            approve(requestId, input) {
                return resolved.distributedRuntime.approvePairRequest(requestId, input ?? {});
            },
            reject(requestId, input) {
                return resolved.distributedRuntime.rejectPairRequest(requestId, input ?? {});
            },
            verify(requestId, challenge, input) {
                return resolved.distributedRuntime.verifyPairRequest(requestId, challenge, input ?? {});
            },
        },
        peers: {
            list(kind, limit = 200) {
                return resolved.distributedRuntime.listPeers(kind, limit);
            },
            get(peerId) {
                return resolved.distributedRuntime.listPeers(undefined, 500).find((peer) => peer.id === peerId) ?? null;
            },
            getSnapshot(peerId) {
                return buildPeerSnapshot(resolved, peerId);
            },
            authenticateToken(tokenValue, remoteAddress) {
                return resolved.distributedRuntime.authenticatePeerToken(tokenValue, remoteAddress);
            },
            heartbeat(auth, input) {
                return resolved.distributedRuntime.heartbeatPeer(auth, input ?? {});
            },
            rotateToken(peerId, input) {
                return resolved.distributedRuntime.rotatePeerToken(peerId, input ?? {});
            },
            revokeToken(peerId, input) {
                return resolved.distributedRuntime.revokePeerToken(peerId, input ?? {});
            },
            disconnect(peerId, input) {
                return resolved.distributedRuntime.disconnectPeer(peerId, input ?? {});
            },
        },
        work: {
            list(limit = 200, peerId) {
                return resolved.distributedRuntime.listWork(limit, peerId);
            },
            enqueue(input) {
                return resolved.distributedRuntime.enqueueWork(input);
            },
            invoke(input) {
                return resolved.distributedRuntime.invokePeer(input);
            },
            claim(auth, input) {
                return resolved.distributedRuntime.claimWork(auth, input ?? {});
            },
            complete(auth, workId, input) {
                return resolved.distributedRuntime.completeWork(auth, workId, input ?? {});
            },
            cancel(workId, input) {
                return resolved.distributedRuntime.cancelWork(workId, input ?? {});
            },
        },
        runners: {
            listPools() {
                return resolved.remoteRunnerRegistry.listPools();
            },
            getPool(poolId) {
                return resolved.remoteRunnerRegistry.getPool(poolId);
            },
            createPool(input) {
                return resolved.remoteRunnerRegistry.createPool(input);
            },
            assignRunnerToPool(poolId, runnerId) {
                return resolved.remoteRunnerRegistry.assignRunnerToPool(poolId, runnerId);
            },
            removeRunnerFromPool(poolId, runnerId) {
                return resolved.remoteRunnerRegistry.removeRunnerFromPool(poolId, runnerId);
            },
            listContracts() {
                return resolved.remoteRunnerRegistry.listContracts();
            },
            getContract(runnerId) {
                return resolved.remoteRunnerRegistry.getContract(runnerId);
            },
            registerContract(contract) {
                return resolved.remoteRunnerRegistry.registerContract(contract);
            },
            upsertContractForAgent(agentId) {
                return resolved.remoteRunnerRegistry.upsertContractForAgent(agentId, resolved.runtimeStore);
            },
            listArtifacts() {
                return resolved.remoteRunnerRegistry.listArtifacts();
            },
            getArtifact(artifactId) {
                return resolved.remoteRunnerRegistry.getArtifact(artifactId);
            },
            captureArtifactForAgent(agentId) {
                return resolved.remoteRunnerRegistry.captureArtifactForAgent(agentId, resolved.runtimeStore);
            },
            captureArtifactForRunner(runnerId) {
                return resolved.remoteRunnerRegistry.captureArtifactForRunner(runnerId, resolved.runtimeStore);
            },
            exportArtifact(artifactId, path) {
                return resolved.remoteRunnerRegistry.exportArtifact(artifactId, path);
            },
            importArtifact(path) {
                return resolved.remoteRunnerRegistry.importArtifact(path);
            },
            buildReviewSummary(artifactId) {
                return resolved.remoteRunnerRegistry.buildReviewSummary(artifactId);
            },
            exportSessionBundle(path) {
                return resolved.remoteRunnerRegistry.exportSessionBundle(resolved.runtimeStore, path);
            },
            importSessionBundle(path) {
                return resolved.remoteRunnerRegistry.importSessionBundle(path);
            },
        },
        getSnapshot() {
            return buildSnapshot(resolved);
        },
        getNodeHostContract() {
            return resolved.distributedRuntime.getNodeHostContract();
        },
    };
}
