/**
 * Read-only service producing derived metrics counts.
 */
import { METRICS_PROJECTION_PUBLIC_SOURCE, } from "./metricsProjectionContract.js";
export class MetricsProjectionService {
    store;
    constructor(store) {
        this.store = store;
    }
    buildMetrics(workspaceId) {
        const runs = this.store.listRunsForWorkspace(workspaceId, 200);
        const reviews = this.store.listReviewQueue(workspaceId);
        const decisions = this.store.listReviewDecisions(workspaceId);
        const repos = this.store.listRepositoryBindings(workspaceId);
        const gates = this.store.listOnboardingGates(workspaceId);
        const settings = this.store.listSettingsReadiness(workspaceId);
        const permissionActivity = this.store.listPermissionActivity({
            workspaceId,
            limit: 50,
        });
        let runsCompleted = 0;
        let runsFailed = 0;
        let runsRunning = 0;
        let runtimeEvents = 0;
        let proofEvidence = 0;
        for (const run of runs) {
            if (run.status === "completed")
                runsCompleted += 1;
            else if (run.status === "failed")
                runsFailed += 1;
            else if (run.status === "running" || run.status === "queued")
                runsRunning += 1;
            runtimeEvents += this.store.listRuntimeEventsForRun(run.id, {
                limit: 200,
            }).events.length;
            if (this.store.findRunEvidence(run.id))
                proofEvidence += 1;
        }
        const decidedReviewIds = new Set(decisions.map((d) => d.reviewId));
        let reviewQueueDecided = 0;
        let reviewQueueOpen = 0;
        for (const r of reviews) {
            if (decidedReviewIds.has(r.id))
                reviewQueueDecided += 1;
            else
                reviewQueueOpen += 1;
        }
        const counts = {
            runsTotal: runs.length,
            runsCompleted,
            runsFailed,
            runsRunning,
            runtimeEvents,
            proofEvidence,
            reviewQueueOpen,
            reviewQueueDecided,
            repositoriesConnected: repos.filter((r) => r.status === "connected")
                .length,
            onboardingReady: gates.filter((g) => g.status === "ready").length,
            settingsReady: settings.filter((s) => s.status === "ready").length,
            permissionActivityRecent: permissionActivity.events.length,
        };
        const hasAny = counts.runsTotal +
            repos.length +
            gates.length +
            settings.length +
            reviews.length +
            permissionActivity.events.length >
            0;
        const reasonCode = !hasAny ? "no-data" : "ok";
        return {
            contractVersion: "v1",
            generatedAt: new Date().toISOString(),
            source: METRICS_PROJECTION_PUBLIC_SOURCE,
            workspaceId,
            reasonCode,
            counts,
        };
    }
}
