/**
 * Apply the deterministic seed dataset to a LocalSqliteStore.
 *
 * Idempotent: re-applying produces the same row counts and stable identifiers.
 * Guards every insert by checking for the seeded row's stable id first so we
 * never duplicate, and so existing live rows (with different ids) are left
 * untouched. No-op when seed is disabled or when the relevant domain flag is
 * off.
 */
import { buildSeedDataset, } from "./seedDataset.js";
export function applySeed(store, config, options = {}) {
    const result = {
        enabled: config.enabled,
        appliedAt: null,
        domains: {
            workspace: emptyDomainResult(),
            runs: emptyDomainResult(),
            runtimeEvents: emptyDomainResult(),
            proofEvidence: emptyDomainResult(),
            permissionActivity: emptyDomainResult(),
            repositories: emptyDomainResult(),
            onboarding: emptyDomainResult(),
            settings: emptyDomainResult(),
            reviewQueue: emptyDomainResult(),
            reviewDecisions: emptyDomainResult(),
        },
    };
    if (!config.enabled)
        return result;
    const dataset = options.dataset ?? buildSeedDataset();
    const anyDomainOn = config.domains.runs ||
        config.domains.runtimeEvents ||
        config.domains.proofEvidence ||
        config.domains.permissionActivity ||
        config.domains.repositories ||
        config.domains.onboarding ||
        config.domains.settings ||
        config.domains.reviewQueue;
    if (!anyDomainOn)
        return result;
    const existingWorkspace = store.findWorkspace(dataset.workspace.id);
    store.upsertWorkspace({
        id: dataset.workspace.id,
        rootPath: dataset.workspace.rootPath,
    });
    if (existingWorkspace) {
        result.domains.workspace.skipped += 1;
    }
    else {
        result.domains.workspace.inserted += 1;
    }
    if (config.domains.runs) {
        for (const run of dataset.runs) {
            applyRun(store, run, result.domains.runs);
        }
    }
    if (config.domains.runtimeEvents) {
        for (const event of dataset.runtimeEvents) {
            applyRuntimeEvent(store, event, result.domains.runtimeEvents);
        }
    }
    if (config.domains.proofEvidence) {
        for (const evidence of dataset.runEvidence) {
            applyProofEvidence(store, evidence, result.domains.proofEvidence);
        }
    }
    if (config.domains.permissionActivity) {
        for (const entry of dataset.permissionEntries) {
            applyPermissionEntry(store, entry, result.domains.permissionActivity);
        }
    }
    if (config.domains.repositories) {
        for (const repo of dataset.repositories) {
            const existing = store
                .listRepositoryBindings(repo.workspaceId)
                .some((row) => row.id === repo.id);
            store.upsertRepositoryBinding({
                id: repo.id,
                workspaceId: repo.workspaceId,
                displayLabel: repo.displayLabel,
                provider: repo.provider,
                status: repo.status,
                ...(repo.lastSyncLabel !== undefined
                    ? { lastSyncLabel: repo.lastSyncLabel }
                    : {}),
                ...(repo.lastErrorCode !== undefined
                    ? { lastErrorCode: repo.lastErrorCode }
                    : {}),
            });
            if (existing)
                result.domains.repositories.skipped += 1;
            else
                result.domains.repositories.inserted += 1;
        }
    }
    if (config.domains.onboarding) {
        for (const gate of dataset.onboardingGates) {
            const existing = store
                .listOnboardingGates(gate.workspaceId)
                .some((row) => row.id === gate.id);
            store.upsertOnboardingGate({
                id: gate.id,
                workspaceId: gate.workspaceId,
                gate: gate.gate,
                status: gate.status,
                tone: gate.tone,
                displayLabel: gate.displayLabel,
                ...(gate.lastErrorCode !== undefined
                    ? { lastErrorCode: gate.lastErrorCode }
                    : {}),
            });
            if (existing)
                result.domains.onboarding.skipped += 1;
            else
                result.domains.onboarding.inserted += 1;
        }
    }
    if (config.domains.settings) {
        for (const area of dataset.settingsReadiness) {
            const existing = store
                .listSettingsReadiness(area.workspaceId)
                .some((row) => row.id === area.id);
            store.upsertSettingsReadiness({
                id: area.id,
                workspaceId: area.workspaceId,
                area: area.area,
                status: area.status,
                tone: area.tone,
                displayLabel: area.displayLabel,
                ...(area.lastErrorCode !== undefined
                    ? { lastErrorCode: area.lastErrorCode }
                    : {}),
            });
            if (existing)
                result.domains.settings.skipped += 1;
            else
                result.domains.settings.inserted += 1;
        }
    }
    if (config.domains.reviewQueue) {
        const baseInstant = new Date("2026-05-21T08:00:00.000Z").getTime();
        for (const entry of dataset.reviewQueue) {
            const existing = store
                .listReviewQueue(entry.workspaceId)
                .some((row) => row.id === entry.id);
            store.upsertReviewQueueEntry({
                id: entry.id,
                workspaceId: entry.workspaceId,
                status: entry.status,
                riskTone: entry.riskTone,
                headline: entry.headline,
                ...(entry.runId !== undefined ? { runId: entry.runId } : {}),
                ...(entry.summaryLabel !== undefined
                    ? { summaryLabel: entry.summaryLabel }
                    : {}),
            });
            if (existing)
                result.domains.reviewQueue.skipped += 1;
            else
                result.domains.reviewQueue.inserted += 1;
        }
        for (const decision of dataset.reviewDecisions) {
            const existing = store
                .listReviewDecisions(decision.workspaceId)
                .some((row) => row.id === decision.id);
            if (!existing) {
                store.insertReviewDecision({
                    id: decision.id,
                    workspaceId: decision.workspaceId,
                    reviewId: decision.reviewId,
                    decision: decision.decision,
                    decidedAt: new Date(baseInstant + decision.decidedAtOffsetMinutes * 60_000).toISOString(),
                    ...(decision.reasonCode !== undefined
                        ? { reasonCode: decision.reasonCode }
                        : {}),
                    ...(decision.noteLabel !== undefined
                        ? { noteLabel: decision.noteLabel }
                        : {}),
                });
                result.domains.reviewDecisions.inserted += 1;
            }
            else {
                result.domains.reviewDecisions.skipped += 1;
            }
        }
    }
    result.appliedAt = new Date().toISOString();
    return result;
}
function emptyDomainResult() {
    return { inserted: 0, skipped: 0 };
}
function applyRun(store, run, domainResult) {
    const existing = store.findRun(run.id);
    if (existing) {
        domainResult.skipped += 1;
        return;
    }
    const input = {
        id: run.id,
        workspaceId: run.workspaceId,
        provider: run.provider,
        status: run.status,
        title: run.title,
    };
    if (run.runtimeSessionId !== undefined)
        input.runtimeSessionId = run.runtimeSessionId;
    if (run.sourceWorkItemId !== undefined)
        input.sourceWorkItemId = run.sourceWorkItemId;
    if (run.sourceRepositoryId !== undefined)
        input.sourceRepositoryId = run.sourceRepositoryId;
    if (run.sourcePreparationId !== undefined)
        input.sourcePreparationId = run.sourcePreparationId;
    if (run.sourceRunIntentId !== undefined)
        input.sourceRunIntentId = run.sourceRunIntentId;
    if (run.branchPlanId !== undefined)
        input.branchPlanId = run.branchPlanId;
    if (run.branchName !== undefined)
        input.branchName = run.branchName;
    if (run.baseBranch !== undefined)
        input.baseBranch = run.baseBranch;
    if (run.capPolicy !== undefined)
        input.capPolicy = run.capPolicy;
    store.createRun(input);
    domainResult.inserted += 1;
}
function applyRuntimeEvent(store, event, domainResult) {
    if (!store.findRun(event.runId)) {
        domainResult.skipped += 1;
        return;
    }
    const page = store.listRuntimeEventsForRun(event.runId, { limit: 100 });
    if (page.events.some((existing) => existing.id === event.id)) {
        domainResult.skipped += 1;
        return;
    }
    const input = {
        id: event.id,
        source: event.source,
        type: event.type,
        occurredAt: event.occurredAt,
        title: event.title,
        description: event.description,
        tone: event.tone,
        runId: event.runId,
    };
    if (event.runtimeSessionId !== undefined)
        input.runtimeSessionId = event.runtimeSessionId;
    if (event.metadata !== undefined)
        input.metadata = event.metadata;
    store.appendRuntimeEvent(input);
    domainResult.inserted += 1;
}
function applyProofEvidence(store, evidence, domainResult) {
    if (!store.findRun(evidence.runId)) {
        domainResult.skipped += 1;
        return;
    }
    const existing = store.findRunEvidence(evidence.runId);
    store.upsertRunEvidence({
        runId: evidence.runId,
        changedFiles: evidence.changedFiles,
        validations: evidence.validations,
        warnings: evidence.warnings,
    });
    if (existing) {
        domainResult.skipped += 1;
    }
    else {
        domainResult.inserted += 1;
    }
}
function applyPermissionEntry(store, entry, domainResult) {
    if (!store.findRun(entry.runId)) {
        domainResult.skipped += 1;
        return;
    }
    if (store.findPermissionDecision(entry.decisionId)) {
        domainResult.skipped += 1;
        return;
    }
    const request = store.upsertPermissionRequest({
        id: entry.requestId,
        workspaceId: SEED_WORKSPACE_ID_GUARD(entry),
        runId: entry.runId,
        provider: "opencode",
        runtimeSessionId: entry.runtimeSessionId,
        request: {
            id: entry.requestId,
            toolCall: {
                id: `${entry.requestId}-call`,
                name: entry.toolName,
                title: entry.toolTitle,
                risk: entry.toolRisk,
                inputPreview: entry.inputPreview,
                affectedPaths: entry.affectedPaths,
            },
            reason: entry.reason,
            options: ["approve_once", "allow_for_session", "deny"],
            policyRecommendation: entry.effect === "allow" ? "ask" : "deny",
        },
        evaluation: { verdict: "requires_approval" },
    });
    store.claimPermissionRequestForReply(request.id);
    store.markPermissionRequestAnswered({
        id: request.id,
        selectedOption: entry.selectedOption,
        opencodeReply: entry.opencodeReply,
        decisionAuditId: entry.auditId,
    });
    store.insertPermissionDecision({
        id: entry.decisionId,
        workspaceId: SEED_WORKSPACE_ID_GUARD(entry),
        runId: entry.runId,
        runtimeSessionId: entry.runtimeSessionId,
        sourcePermissionRequestId: request.id,
        scope: entry.scope,
        effect: entry.effect,
        option: entry.option,
        capabilities: entry.capabilities,
        pattern: entry.pattern,
        toolName: entry.toolName,
        toolTitle: entry.toolTitle,
        toolRisk: entry.toolRisk,
        inputPreview: entry.inputPreview,
        affectedPaths: entry.affectedPaths,
        auditId: entry.auditId,
    });
    domainResult.inserted += 1;
}
function SEED_WORKSPACE_ID_GUARD(entry) {
    void entry;
    return "ws-seed-local";
}
