/**
 * `olam seed <subcommand>` — operator-facing CRUD for postgres seed templates.
 *
 * Phase A task A1 of `olam-hybrid-shared-postgres`. The hybrid path's
 * `services.postgres.seed_template:` field in `.olam.yaml` references named
 * template DBs on the operator's `olam-postgres` singleton. This command is
 * the canonical way to populate, inspect, and remove those templates.
 *
 * Subcommands:
 *   bake    — pg_dump a source DB into the singleton as a new template
 *   list    — list seed-template DBs on the singleton
 *   remove  — DROP a seed template (refuses if any per-world clones exist)
 *   verify  — sanity-check a seed (existence, connectivity, size)
 *
 * Source modes for `bake`:
 *   --source-container <name>      docker exec pg_dump inside a running container
 *   --source-url <postgres-url>    pg_dump via libpq URL (host pg, neon, etc.)
 *   --source-local <db>            pg_dump a DB that already lives on the singleton
 *
 * Generic across projects — atlas-core's `atlas_common_seed` /
 * `atlas_merchant_seed`, atlas-pay's `atlas_pay_seed`, and any future repo's
 * named seeds all flow through this same surface. No atlas-specific knowledge
 * embedded.
 */
import { spawnSync, spawn as spawnAsync } from 'node:child_process';
import { printError, printSuccess, printInfo, printHeader, printWarning } from '../output.js';
const DEFAULT_SINGLETON_CONTAINER = 'olam-postgres';
const DEFAULT_SINGLETON_USER = 'development';
// ── helpers ─────────────────────────────────────────────────────────
/**
 * Validate a seed name. Names map 1:1 to postgres DB identifiers, so they
 * must be plain alphanumeric + underscore (matches `[a-z][a-z0-9_]*`).
 * Hyphens are rejected — `CREATE DATABASE "foo-bar"` requires double-quoting
 * everywhere downstream which is brittle.
 */
function assertValidSeedName(name) {
    if (!/^[a-z][a-z0-9_]*$/.test(name)) {
        throw new Error(`invalid seed name "${name}" — must match [a-z][a-z0-9_]* (no hyphens, no uppercase)`);
    }
}
function singletonDocker(container, user, args, stdin) {
    return spawnSync('docker', ['exec', '-i', container, 'psql', '-U', user, ...args], { encoding: 'utf-8', input: stdin });
}
function singletonHasDb(container, user, db) {
    const r = singletonDocker(container, user, [
        '-d', 'postgres', '-tAc',
        `SELECT 1 FROM pg_database WHERE datname='${db.replace(/'/g, "''")}'`,
    ]);
    return r.status === 0 && (r.stdout || '').trim() === '1';
}
function singletonListSeeds(container, user) {
    const r = singletonDocker(container, user, [
        '-d', 'postgres', '-tAc',
        "SELECT datname || '|' || pg_size_pretty(pg_database_size(datname)) " +
            "FROM pg_database WHERE datname LIKE '%\\_seed' ORDER BY datname",
    ]);
    if (r.status !== 0) {
        throw new Error(`failed to list seeds: ${(r.stderr || '').trim()}`);
    }
    const lines = (r.stdout || '').trim().split('\n').filter((l) => l.length > 0);
    return lines.map((line) => {
        const [name = '', size = ''] = line.split('|');
        return { name, size };
    });
}
function singletonListClonesOf(container, user, seed) {
    // World clones derive from `<seed-without-_seed>_world_<id>` per
    // deriveWorldDbName in core/src/world/manager.ts.
    const prefix = seed.endsWith('_seed') ? seed.slice(0, -'_seed'.length) : seed;
    const r = singletonDocker(container, user, [
        '-d', 'postgres', '-tAc',
        `SELECT datname FROM pg_database WHERE datname LIKE '${prefix.replace(/'/g, "''")}_world_%' ORDER BY datname`,
    ]);
    if (r.status !== 0)
        return [];
    return (r.stdout || '').trim().split('\n').filter((l) => l.length > 0);
}
// ── bake ────────────────────────────────────────────────────────────
async function handleBake(opts) {
    assertValidSeedName(opts.as);
    const singleton = opts.singletonContainer ?? DEFAULT_SINGLETON_CONTAINER;
    const singletonUser = opts.singletonUser ?? DEFAULT_SINGLETON_USER;
    // Mode resolution — exactly one source must be set.
    const sources = [opts.sourceContainer, opts.sourceUrl, opts.sourceLocal].filter(Boolean);
    if (sources.length === 0) {
        throw new Error('no source specified — pass exactly one of --source-container, --source-url, --source-local');
    }
    if (sources.length > 1) {
        throw new Error('multiple sources specified — pass exactly one of --source-container, --source-url, --source-local');
    }
    // Pre-flight: singleton container reachable?
    const ping = spawnSync('docker', ['inspect', '--format', '{{.State.Status}}', singleton], { encoding: 'utf-8' });
    if (ping.status !== 0 || (ping.stdout || '').trim() !== 'running') {
        throw new Error(`singleton container "${singleton}" not running — run \`olam bootstrap\` first`);
    }
    // Already exists?
    if (singletonHasDb(singleton, singletonUser, opts.as)) {
        if (!opts.force) {
            throw new Error(`seed "${opts.as}" already exists — pass --force to overwrite (DROP + recreate)`);
        }
        // Check for active clones first; refuse drop if any.
        const clones = singletonListClonesOf(singleton, singletonUser, opts.as);
        if (clones.length > 0) {
            throw new Error(`cannot --force overwrite "${opts.as}" — ${clones.length} per-world clone(s) still depend on it: ${clones.join(', ')}\n` +
                `Destroy those worlds first, then re-bake.`);
        }
        printWarning(`Dropping existing seed "${opts.as}" (--force)`);
        const drop = singletonDocker(singleton, singletonUser, ['-d', 'postgres', '-c', `DROP DATABASE "${opts.as}"`]);
        if (drop.status !== 0) {
            throw new Error(`DROP DATABASE failed: ${(drop.stderr || '').trim()}`);
        }
    }
    process.stdout.write(`  Creating empty target DB "${opts.as}" on singleton\n`);
    const create = singletonDocker(singleton, singletonUser, ['-d', 'postgres', '-c', `CREATE DATABASE "${opts.as}"`]);
    if (create.status !== 0) {
        throw new Error(`CREATE DATABASE "${opts.as}" failed: ${(create.stderr || '').trim()}`);
    }
    // Pipe pg_dump → singleton psql. Use spawn (not spawnSync) so the stream
    // can flow without buffering the whole dump in memory.
    let dumpArgs;
    // Initialised to the same minimal-PATH shape that every branch below sets;
    // the spread of `process.env` (typed `string | undefined`) tripped tsc
    // strict-mode and was always overwritten anyway.
    let dumpEnv = { PATH: process.env['PATH'] || '' };
    if (opts.sourceContainer) {
        const srcDb = opts.sourceDb ?? 'postgres';
        const srcUser = opts.sourceUser ?? DEFAULT_SINGLETON_USER;
        process.stdout.write(`  Source: container ${opts.sourceContainer} DB=${srcDb} user=${srcUser}\n`);
        dumpArgs = ['exec', opts.sourceContainer, 'pg_dump', '-U', srcUser, '-d', srcDb, '--no-owner', '--no-privileges'];
        dumpEnv = { PATH: process.env['PATH'] || '' };
    }
    else if (opts.sourceLocal) {
        if (!singletonHasDb(singleton, singletonUser, opts.sourceLocal)) {
            throw new Error(`--source-local "${opts.sourceLocal}" does not exist on singleton`);
        }
        process.stdout.write(`  Source: singleton local DB ${opts.sourceLocal}\n`);
        dumpArgs = ['exec', singleton, 'pg_dump', '-U', singletonUser, '-d', opts.sourceLocal, '--no-owner', '--no-privileges'];
        dumpEnv = { PATH: process.env['PATH'] || '' };
    }
    else {
        // sourceUrl
        process.stdout.write(`  Source: ${opts.sourceUrl.replace(/\/\/[^:]+:[^@]+@/, '//<creds>@')}\n`);
        dumpArgs = ['exec', '-e', `PGURL=${opts.sourceUrl}`, singleton, 'sh', '-c', 'pg_dump --no-owner --no-privileges "$PGURL"'];
        dumpEnv = { PATH: process.env['PATH'] || '' };
    }
    const dumper = spawnAsync('docker', dumpArgs, { stdio: ['ignore', 'pipe', 'inherit'], env: dumpEnv });
    const loader = spawnAsync('docker', ['exec', '-i', singleton, 'psql', '-U', singletonUser, '-d', opts.as, '-v', 'ON_ERROR_STOP=1', '-q'], { stdio: ['pipe', 'inherit', 'inherit'], env: { PATH: process.env['PATH'] || '' } });
    dumper.stdout.pipe(loader.stdin);
    const [dumpExit, loadExit] = await Promise.all([
        new Promise((res) => dumper.on('close', (code) => res(code ?? 1))),
        new Promise((res) => loader.on('close', (code) => res(code ?? 1))),
    ]);
    if (dumpExit !== 0) {
        throw new Error(`pg_dump exited with code ${dumpExit}`);
    }
    if (loadExit !== 0) {
        throw new Error(`psql load exited with code ${loadExit}`);
    }
    // Verify
    const size = singletonDocker(singleton, singletonUser, [
        '-d', 'postgres', '-tAc',
        `SELECT pg_size_pretty(pg_database_size('${opts.as}'))`,
    ]);
    const sizeStr = (size.stdout || '').trim() || 'unknown';
    printSuccess(`Seed "${opts.as}" baked (${sizeStr})`);
}
// ── list ────────────────────────────────────────────────────────────
function handleList(opts) {
    const singleton = opts.singletonContainer ?? DEFAULT_SINGLETON_CONTAINER;
    const singletonUser = opts.singletonUser ?? DEFAULT_SINGLETON_USER;
    const seeds = singletonListSeeds(singleton, singletonUser);
    if (opts.json) {
        process.stdout.write(JSON.stringify(seeds, null, 2) + '\n');
        return;
    }
    if (seeds.length === 0) {
        process.stdout.write('No seeds found on singleton.\n');
        return;
    }
    printHeader(`${seeds.length} seed(s) on ${singleton}`);
    const nameWidth = Math.max(...seeds.map((s) => s.name.length), 4);
    for (const s of seeds) {
        process.stdout.write(`  ${s.name.padEnd(nameWidth)}  ${s.size}\n`);
    }
}
// ── remove ──────────────────────────────────────────────────────────
function handleRemove(name, opts) {
    assertValidSeedName(name);
    const singleton = opts.singletonContainer ?? DEFAULT_SINGLETON_CONTAINER;
    const singletonUser = opts.singletonUser ?? DEFAULT_SINGLETON_USER;
    if (!singletonHasDb(singleton, singletonUser, name)) {
        printWarning(`Seed "${name}" does not exist on singleton — nothing to do`);
        return;
    }
    const clones = singletonListClonesOf(singleton, singletonUser, name);
    if (clones.length > 0 && !opts.force) {
        throw new Error(`seed "${name}" has ${clones.length} active world clone(s): ${clones.join(', ')}\n` +
            `Destroy those worlds first, or re-run with --force to drop anyway (CAUTION: leaves world DBs orphaned).`);
    }
    const drop = singletonDocker(singleton, singletonUser, ['-d', 'postgres', '-c', `DROP DATABASE "${name}"`]);
    if (drop.status !== 0) {
        throw new Error(`DROP DATABASE "${name}" failed: ${(drop.stderr || '').trim()}`);
    }
    printSuccess(`Removed seed "${name}"`);
}
// ── verify ──────────────────────────────────────────────────────────
function handleVerify(name, opts) {
    assertValidSeedName(name);
    const singleton = opts.singletonContainer ?? DEFAULT_SINGLETON_CONTAINER;
    const singletonUser = opts.singletonUser ?? DEFAULT_SINGLETON_USER;
    if (!singletonHasDb(singleton, singletonUser, name)) {
        throw new Error(`seed "${name}" does not exist on singleton`);
    }
    // Heartbeat: run a trivial SELECT to prove connectivity + accessibility.
    const heartbeat = singletonDocker(singleton, singletonUser, ['-d', name, '-tAc', 'SELECT 1']);
    if (heartbeat.status !== 0 || (heartbeat.stdout || '').trim() !== '1') {
        throw new Error(`heartbeat failed: ${(heartbeat.stderr || '').trim()}`);
    }
    // Size + table count for visibility.
    const meta = singletonDocker(singleton, singletonUser, [
        '-d', name, '-tAc',
        "SELECT pg_size_pretty(pg_database_size(current_database())) || '|' || " +
            "(SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public')",
    ]);
    const [size = '?', tableCount = '?'] = (meta.stdout || '').trim().split('|');
    const clones = singletonListClonesOf(singleton, singletonUser, name);
    printSuccess(`Seed "${name}" OK`);
    printInfo('size', size);
    printInfo('tables', `${tableCount} (public schema)`);
    printInfo('clones', `${clones.length}${clones.length > 0 ? ' (' + clones.join(', ') + ')' : ''}`);
}
// ── register ────────────────────────────────────────────────────────
export function registerSeed(program) {
    const seed = program
        .command('seed')
        .description('Manage postgres seed templates on the olam-postgres singleton');
    seed
        .command('bake')
        .description('Bake a source DB into the singleton as a named seed template')
        .requiredOption('--as <name>', 'Target seed name (e.g. atlas_common_seed); [a-z][a-z0-9_]*')
        .option('--source-container <name>', 'Source: pg_dump inside this docker container')
        .option('--source-url <url>', 'Source: pg_dump via postgres:// URL (libpq)')
        .option('--source-local <db>', 'Source: pg_dump a DB already on the singleton')
        .option('--source-db <db>', 'DB name to dump (when --source-container; default: postgres)')
        .option('--source-user <user>', 'Source-side user (when --source-container; default: development)')
        .option('--singleton-container <name>', 'Override singleton container name (default: olam-postgres)')
        .option('--singleton-user <user>', 'Override singleton user (default: development)')
        .option('--force', 'Drop + recreate if the seed already exists')
        .action(async (opts) => {
        try {
            await handleBake(opts);
        }
        catch (err) {
            printError(err instanceof Error ? err.message : String(err));
            process.exit(1);
        }
    });
    seed
        .command('list')
        .description('List seed templates on the singleton')
        .option('--json', 'Emit machine-parseable JSON')
        .option('--singleton-container <name>', 'Override singleton container name (default: olam-postgres)')
        .option('--singleton-user <user>', 'Override singleton user (default: development)')
        .action((opts) => {
        try {
            handleList(opts);
        }
        catch (err) {
            printError(err instanceof Error ? err.message : String(err));
            process.exit(1);
        }
    });
    seed
        .command('remove <name>')
        .description('Remove a seed template (refuses by default if any per-world clones exist)')
        .option('--force', 'DROP even if active clones exist (clones will be orphaned)')
        .option('--singleton-container <name>', 'Override singleton container name (default: olam-postgres)')
        .option('--singleton-user <user>', 'Override singleton user (default: development)')
        .action((name, opts) => {
        try {
            handleRemove(name, opts);
        }
        catch (err) {
            printError(err instanceof Error ? err.message : String(err));
            process.exit(1);
        }
    });
    seed
        .command('verify <name>')
        .description('Sanity-check a seed (existence, connectivity, size, clone count)')
        .option('--singleton-container <name>', 'Override singleton container name (default: olam-postgres)')
        .option('--singleton-user <user>', 'Override singleton user (default: development)')
        .action((name, opts) => {
        try {
            handleVerify(name, opts);
        }
        catch (err) {
            printError(err instanceof Error ? err.message : String(err));
            process.exit(1);
        }
    });
}
//# sourceMappingURL=seed.js.map