/**
 * Seed loader smoke.
 *
 * Boots an in-process LocalSqliteStore using `:memory:`, applies the seed
 * twice with all domain flags enabled, and asserts:
 *  - first apply inserts the expected counts;
 *  - second apply inserts nothing and skips the same number of rows;
 *  - the seed status formatter response contains no unsafe sentinels.
 *
 * The smoke does not start the bridge HTTP server, OpenCode runtime, or any
 * external service. It is a thin permission-safe verification that the seed
 * loader and diagnostics stay deterministic, idempotent, and redaction-safe
 * across two invocations on the same store.
 */
import { summarizeSeedConfig, } from "../config/bridgeConfig.js";
import { LocalSqliteStore } from "../persistence/LocalSqliteStore.js";
import { applySeed, } from "../persistence/seed/applySeed.js";
import { formatSeedStatus } from "../http/seedStatus.js";
const UNSAFE_PATTERNS = [
    /\bsk-[A-Za-z0-9_-]{6,}\b/u,
    /\bBearer\s+[A-Za-z0-9._~-]{8,}\b/iu,
    /patchTrailLocalHandoff=/iu,
    /\/Users\/[^\s]+/u,
    /\.sqlite\b/iu,
];
export async function runSeedSmoke() {
    const store = await LocalSqliteStore.open(":memory:");
    try {
        const config = {
            enabled: true,
            domains: {
                runs: true,
                runtimeEvents: true,
                proofEvidence: true,
                permissionActivity: true,
                repositories: true,
                onboarding: true,
                settings: true,
                reviewQueue: true,
            },
        };
        const first = applySeed(store, config);
        assertEnabled(first, "first apply must report enabled=true");
        assertInserted(first, "first apply must insert workspace+runs+events");
        const second = applySeed(store, config);
        assertEnabled(second, "second apply must report enabled=true");
        assertIdempotent(first, second);
        // Diagnostics scan
        const payload = formatSeedStatus({
            current: second,
            set: () => undefined,
        });
        const serialized = JSON.stringify(payload);
        for (const pattern of UNSAFE_PATTERNS) {
            if (pattern.test(serialized)) {
                throw new Error(`seed status payload leaked unsafe sentinel matching ${pattern}`);
            }
        }
        const summary = summarizeSeedConfig(config);
        return {
            status: "passed",
            appliedAtFirst: first.appliedAt,
            appliedAtSecond: second.appliedAt,
            enabledDomains: summary.enabledDomains,
            firstCounts: countsOnly(first),
            secondCounts: countsOnly(second),
        };
    }
    finally {
        store.close();
    }
}
export async function main(argv = process.argv.slice(2)) {
    const wantsJson = argv.includes("--json");
    try {
        const summary = await runSeedSmoke();
        if (wantsJson) {
            process.stdout.write(`${JSON.stringify(summary)}\n`);
            return;
        }
        process.stdout.write(`Seed smoke passed: domains=${summary.enabledDomains.join(",")} firstAt=${summary.appliedAtFirst} secondAt=${summary.appliedAtSecond}\n`);
    }
    catch (error) {
        const message = error instanceof Error ? error.message : "Seed smoke failed.";
        process.stderr.write(wantsJson
            ? `${JSON.stringify({ status: "failed", error: message })}\n`
            : `${message}\n`);
        process.exitCode = 1;
    }
}
function assertEnabled(result, label) {
    if (!result.enabled)
        throw new Error(label);
}
function assertInserted(result, label) {
    if (result.domains.workspace.inserted < 1)
        throw new Error(`${label}: workspace inserted < 1`);
    if (result.domains.runs.inserted < 1)
        throw new Error(`${label}: runs inserted < 1`);
    if (result.domains.runtimeEvents.inserted < 1)
        throw new Error(`${label}: runtimeEvents inserted < 1`);
    if (result.domains.proofEvidence.inserted < 1)
        throw new Error(`${label}: proofEvidence inserted < 1`);
    if (result.domains.permissionActivity.inserted < 1)
        throw new Error(`${label}: permissionActivity inserted < 1`);
}
function assertIdempotent(first, second) {
    for (const domain of [
        "workspace",
        "runs",
        "runtimeEvents",
        "proofEvidence",
        "permissionActivity",
    ]) {
        if (second.domains[domain].inserted !== 0) {
            throw new Error(`idempotency violated: ${domain} inserted=${second.domains[domain].inserted} on second apply`);
        }
        if (second.domains[domain].skipped !== first.domains[domain].inserted) {
            throw new Error(`idempotency violated: ${domain} skipped=${second.domains[domain].skipped} expected ${first.domains[domain].inserted}`);
        }
    }
}
function countsOnly(result) {
    return {
        workspace: { ...result.domains.workspace },
        runs: { ...result.domains.runs },
        runtimeEvents: { ...result.domains.runtimeEvents },
        proofEvidence: { ...result.domains.proofEvidence },
        permissionActivity: { ...result.domains.permissionActivity },
    };
}
