import { spawn } from "child_process";
import { InstanceStateManager } from "../lib/dev/index.js";
export async function psqlCommand(databaseName) {
    const stateManager = new InstanceStateManager(process.cwd());
    await stateManager.cleanStaleState();
    const existingInstances = await stateManager.getExistingInstances();
    if (!existingInstances) {
        console.error("Error: No running instances found. Run `specific dev` first.");
        process.exit(1);
    }
    const availableDatabases = Object.keys(existingInstances.databases);
    if (availableDatabases.length === 0) {
        console.error("Error: No databases found in running instances.");
        process.exit(1);
    }
    let targetDb;
    if (databaseName) {
        if (!existingInstances.databases[databaseName]) {
            console.error(`Error: Database "${databaseName}" not found. Available: ${availableDatabases.join(", ")}`);
            process.exit(1);
        }
        targetDb = databaseName;
    }
    else {
        if (availableDatabases.length > 1) {
            console.error(`Error: Multiple databases available. Specify one: ${availableDatabases.join(", ")}`);
            process.exit(1);
        }
        targetDb = availableDatabases[0];
    }
    const dbState = existingInstances.databases[targetDb];
    const child = spawn("psql", ["-h", dbState.host, "-p", String(dbState.port), "-U", dbState.user, "-d", dbState.dbName], {
        cwd: process.cwd(),
        env: {
            ...process.env,
            PGPASSWORD: dbState.password,
        },
        stdio: "inherit",
    });
    child.on("exit", (code, signal) => {
        if (signal) {
            process.kill(process.pid, signal);
        }
        else {
            process.exit(code ?? 0);
        }
    });
    child.on("error", (err) => {
        console.error(`Error: Failed to start psql: ${err.message}`);
        process.exit(1);
    });
}
//# sourceMappingURL=psql.js.map