import { serializeMemoryRows } from '../serializers/memory-serializer.js';
import { serializeRuns } from '../serializers/run-serializer.js';
import { collectDashboardBaseState } from './summary-selector.js';
export async function buildOperateSurface(ctx, url) {
    const state = collectDashboardBaseState(ctx, url);
    return {
        repoIdentity: state.snapshot?.repoIdentity ?? ctx.getSelectedRepoIdentity(url),
        runs: serializeRuns(state.runtime?.listRuns?.(12) ?? []),
        usage: state.usage,
        tokenOptimization: state.tokenOptimization,
        sourceAwareTokenBudget: state.snapshot?.sourceAwareTokenBudget ?? state.runtime?.getUsageSnapshot?.()?.sourceAwareTokenBudget ?? {},
        agentFlow: state.snapshot?.instructionPacket?.selectionPlan?.executionPolicy?.agentFlow
            ?? state.snapshot?.executionLedger?.agentFlow
            ?? state.runtime?.getUsageSnapshot?.()?.selectionPlan?.executionPolicy?.agentFlow
            ?? {},
        gateSummary: state.gateSummary,
        memoryContainers: state.memoryContainers,
        interpretationIssues: state.interpretationIssues,
        orchestrationSession: state.snapshot?.orchestration ?? state.orchestrator?.getSessionState?.() ?? {},
        orchestrationLedger: state.snapshot?.executionLedger ?? state.runtime?.getExecutionLedger?.() ?? {},
        instructionPacket: state.snapshot?.instructionPacket ?? state.runtime?.getInstructionPacket?.() ?? {},
        tokensSummary: state.snapshot?.tokens ?? state.runtime?.getTokenTelemetrySummary?.() ?? {},
        tokensTimeline: state.snapshot?.tokens?.timeline ?? state.runtime?.getTokenTelemetryTimeline?.(12) ?? [],
        tokensBySource: state.snapshot?.tokens?.bySourceClass ?? state.runtime?.getTokenTelemetrySummary?.()?.bySourceClass ?? {},
        memory: serializeMemoryRows(ctx.listDashboardMemories({ limit: 12 })),
        memoryHealth: state.memoryHealth,
        memoryShared: state.snapshot?.runtimeId && state.runtime?.getRuntimeId?.() === state.snapshot.runtimeId
            ? state.runtime.getSharedMemorySnapshot?.(8) ?? []
            : [],
        clients: state.snapshot?.clients?.detected?.length
            ? state.snapshot.clients.detected
            : ctx.getClientRegistry()?.listClients(ctx.getAdapters()) ?? [],
        primaryClient: state.snapshot?.clients?.primary ?? ctx.getClientRegistry()?.getPrimaryClient(ctx.getAdapters()) ?? null,
    };
}
