import { NexusLayerAdapter } from '../../engines/nexus-layer.js';
export function collectDashboardBaseState(ctx, url) {
    const snapshot = ctx.resolveRuntimeSnapshot(url);
    const runtime = ctx.getRuntime();
    const orchestrator = ctx.getOrchestrator();
    const memory = ctx.getMemory();
    const usage = ctx.collectUsageSnapshot(url);
    const layer = memory ? new NexusLayerAdapter(memory, runtime, orchestrator) : null;
    const latestRun = snapshot?.runtimeId && runtime?.getRuntimeId?.() === snapshot.runtimeId
        ? runtime?.listRuns?.(1)?.[0] ?? usage?.latestRun ?? null
        : usage?.latestRun ?? null;
    const memoryHealth = runtime?.getMemoryHealth?.() ?? memory?.getHealthSummary?.() ?? {
        generatedAt: Date.now(),
        schemaVersion: 0,
        total: 0,
        active: 0,
        quarantined: 0,
        scrap: 0,
        expired: 0,
        promoted: 0,
        shared: 0,
        purgeEligible: 0,
        quarantineBacklog: 0,
        lastHygieneAt: null,
        topTags: [],
    };
    const memoryContainers = memory?.getContainerSummary?.(snapshot?.orchestration?.sessionId) ?? null;
    const tokenOptimization = ctx.collectTokenOptimization(snapshot, usage);
    const gateSummary = ctx.collectGateSummary(latestRun);
    const interpretationIssues = ctx.collectInterpretationIssues({ usage, latestRun, memoryHealth });
    return {
        snapshot,
        runtime,
        orchestrator,
        memory,
        usage,
        layer,
        latestRun,
        memoryHealth,
        memoryContainers,
        tokenOptimization,
        gateSummary,
        interpretationIssues,
    };
}
export async function buildDashboardSummary(ctx, url) {
    const state = collectDashboardBaseState(ctx, url);
    const repoIdentity = state.snapshot?.repoIdentity ?? ctx.getSelectedRepoIdentity(url);
    const health = await ctx.getCachedValue('health', 15_000, () => ctx.collectHealth());
    const canonicalHealth = repoIdentity && typeof repoIdentity === 'object'
        ? {
            ...health,
            projectName: repoIdentity.repoName || health.projectName,
            repoIdentity: {
                ...(health.repoIdentity ?? {}),
                ...repoIdentity,
            },
            scanContext: health.scanContext
                ? {
                    ...health.scanContext,
                    repoRoot: repoIdentity.repoRoot || health.scanContext.repoRoot,
                    workspaceRoot: repoIdentity.workspaceRoot || health.scanContext.workspaceRoot,
                    workspaceSource: repoIdentity.workspaceSource || health.scanContext.workspaceSource,
                    workspaceStateKey: repoIdentity.workspaceStateKey || health.scanContext.workspaceStateKey,
                }
                : health.scanContext,
        }
        : health;
    const sharedMemory = state.snapshot?.runtimeId && state.runtime?.getRuntimeId?.() === state.snapshot.runtimeId
        ? state.runtime.getSharedMemorySnapshot?.(12) ?? []
        : [];
    const ragCollections = state.orchestrator?.listRagCollections?.() ?? [];
    return {
        generatedAt: Date.now(),
        selectedRuntimeId: state.usage?.runtimeId ?? state.runtime?.getRuntimeId?.() ?? null,
        repoIdentity,
        health: canonicalHealth,
        runtimes: ctx.runtimeRegistry.list(),
        usage: state.usage,
        latestRun: state.latestRun,
        orchestrationSession: state.snapshot?.orchestration ?? state.orchestrator?.getSessionState?.() ?? {},
        memoryHealth: state.memoryHealth,
        memoryShared: sharedMemory,
        memoryContainers: state.memoryContainers,
        gateSummary: state.gateSummary,
        tokenOptimization: state.tokenOptimization,
        interpretationIssues: state.interpretationIssues,
        preCompactionBackup: state.memory?.getLastPreCompactionBackup?.() ?? null,
        backends: state.runtime?.getBackendCatalog?.() ?? {},
        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,
        nexusLayer: state.layer?.getSummary(state.snapshot?.orchestration?.sessionId) ?? null,
        ragCollections,
        ragAttachedCount: ragCollections.filter((collection) => collection.attached).length,
        patterns: state.orchestrator?.listPatterns?.()?.slice(0, 5) ?? [],
        alerts: ctx.buildDashboardAlerts({
            health,
            usage: state.usage,
            memoryHealth: state.memoryHealth,
        }),
    };
}
