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 compact = url.searchParams.get('detail') === 'compact';
    const snapshot = (ctx.resolveRuntimeSnapshot(url) ?? {});
    const runtime = ctx.getRuntime();
    const orchestrator = ctx.getOrchestrator();
    const usage = ctx.collectUsageSnapshot(url);
    const runtimeUsage = (runtime?.getUsageSnapshot?.() ?? {});
    const orchestrationSession = snapshot?.orchestration ?? orchestrator?.getSessionState?.() ?? {};
    const orchestrationLedger = snapshot?.executionLedger ?? runtime?.getExecutionLedger?.() ?? {};
    const instructionPacket = snapshot?.instructionPacket ?? runtime?.getInstructionPacket?.() ?? {};
    const modelRoute = instructionPacket?.selectionPlan?.modelRoute
        ?? orchestrationLedger?.selectionPlan?.modelRoute
        ?? runtimeUsage?.selectionPlan?.modelRoute
        ?? {};
    if (compact) {
        const latestRun = snapshot?.runtimeId && runtime?.getRuntimeId?.() === snapshot.runtimeId
            ? runtime?.listRuns?.(1)?.[0] ?? usage?.latestRun ?? null
            : usage?.latestRun ?? null;
        const memoryHealth = runtime?.getMemoryHealth?.() ?? {
            total: 0,
            active: 0,
            promoted: 0,
            recentPromotions: [],
        };
        const tokenOptimization = ctx.collectTokenOptimization(snapshot, usage);
        return {
            repoIdentity: snapshot?.repoIdentity ?? ctx.getSelectedRepoIdentity(url),
            runs: serializeRuns(runtime?.listRuns?.(12) ?? []),
            usage,
            tokenOptimization,
            sourceAwareTokenBudget: snapshot?.sourceAwareTokenBudget ?? runtimeUsage.sourceAwareTokenBudget ?? {},
            modelRoute,
            agentFlow: instructionPacket?.selectionPlan?.executionPolicy?.agentFlow
                ?? orchestrationLedger?.agentFlow
                ?? runtimeUsage?.selectionPlan?.executionPolicy?.agentFlow
                ?? {},
            gateSummary: ctx.collectGateSummary(latestRun),
            memoryContainers: null,
            interpretationIssues: ctx.collectInterpretationIssues({ usage, latestRun, memoryHealth }),
            orchestration: {
                sessionId: orchestrationSession?.sessionId,
                runId: orchestrationSession?.runId ?? usage?.latestRun?.runId,
                state: orchestrationSession?.state ?? usage?.latestRun?.status,
                planningContext: orchestrationSession?.planningContext,
                workerPlan: orchestrationSession?.workerPlan ?? runtimeUsage?.workerPlan,
                autoGhostPass: orchestrationSession?.autoGhostPass ?? runtimeUsage?.autoGhostPass,
            },
            orchestrationSession: orchestrationSession
                ? {
                    sessionId: orchestrationSession.sessionId,
                    runId: orchestrationSession.runId,
                    state: orchestrationSession.state,
                }
                : {},
            orchestrationLedger: {},
            instructionPacket: instructionPacket?.selectionPlan
                ? {
                    selectionPlan: {
                        modelRoute: instructionPacket.selectionPlan.modelRoute,
                        contextRouter: instructionPacket.selectionPlan.contextRouter,
                        selected: instructionPacket.selectionPlan.selected,
                    },
                }
                : {},
            tokensSummary: snapshot?.tokens ?? runtime?.getTokenTelemetrySummary?.() ?? {},
            tokensTimeline: snapshot?.tokens?.timeline?.slice?.(0, 8) ?? runtime?.getTokenTelemetryTimeline?.(8) ?? [],
            tokensBySource: snapshot?.tokens?.bySourceClass ?? runtime?.getTokenTelemetrySummary?.()?.bySourceClass ?? {},
            memory: [],
            memorySummary: {
                total: memoryHealth?.total ?? 0,
                active: memoryHealth?.active ?? 0,
                promoted: memoryHealth?.promoted ?? 0,
            },
            memoryHealth: {
                total: memoryHealth?.total ?? 0,
                active: memoryHealth?.active ?? 0,
                recentPromotions: memoryHealth?.recentPromotions?.slice?.(0, 4) ?? [],
            },
            clients: snapshot?.clients?.detected ?? [],
            primaryClient: snapshot?.clients?.primary ?? null,
            memoryShared: [],
        };
    }
    const state = collectDashboardBaseState(ctx, url);
    const fullUsage = state.usage ?? {};
    const fullSnapshot = state.snapshot ?? {};
    const fullRuntimeUsage = state.runtime?.getUsageSnapshot?.() ?? {};
    const fullOrchestrationSession = fullSnapshot.orchestration ?? state.orchestrator?.getSessionState?.() ?? {};
    const fullOrchestrationLedger = fullSnapshot.executionLedger ?? state.runtime?.getExecutionLedger?.() ?? {};
    const fullInstructionPacket = fullSnapshot.instructionPacket ?? state.runtime?.getInstructionPacket?.() ?? {};
    const fullModelRoute = fullInstructionPacket?.selectionPlan?.modelRoute
        ?? fullOrchestrationLedger?.selectionPlan?.modelRoute
        ?? fullRuntimeUsage?.selectionPlan?.modelRoute
        ?? {};
    return {
        repoIdentity: fullSnapshot.repoIdentity ?? ctx.getSelectedRepoIdentity(url),
        runs: serializeRuns(state.runtime?.listRuns?.(12) ?? []),
        usage: fullUsage,
        tokenOptimization: state.tokenOptimization,
        sourceAwareTokenBudget: fullSnapshot.sourceAwareTokenBudget ?? fullRuntimeUsage.sourceAwareTokenBudget ?? {},
        modelRoute: fullModelRoute,
        agentFlow: fullInstructionPacket?.selectionPlan?.executionPolicy?.agentFlow
            ?? fullOrchestrationLedger?.agentFlow
            ?? fullRuntimeUsage?.selectionPlan?.executionPolicy?.agentFlow
            ?? {},
        gateSummary: state.gateSummary,
        memoryContainers: state.memoryContainers,
        interpretationIssues: state.interpretationIssues,
        orchestrationSession: fullOrchestrationSession,
        orchestrationLedger: fullOrchestrationLedger,
        instructionPacket: fullInstructionPacket,
        tokensSummary: fullSnapshot.tokens ?? state.runtime?.getTokenTelemetrySummary?.() ?? {},
        tokensTimeline: fullSnapshot.tokens?.timeline ?? state.runtime?.getTokenTelemetryTimeline?.(12) ?? [],
        tokensBySource: fullSnapshot.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,
    };
}
