import { formatTable } from "./pglite-command-DW75eubZ.js";
function ok(stdout) {
  return { stdout, stderr: "", exitCode: 0 };
}
function err(stderr) {
  return { stdout: "", stderr, exitCode: 1 };
}
function parsePgArgs(args) {
  let json = false;
  let db;
  const rest = [];
  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    if (arg === "--json") {
      json = true;
    } else if (arg === "--db" && i + 1 < args.length) {
      db = args[++i];
    } else if (arg.startsWith("--db=")) {
      db = arg.slice(5);
    } else {
      rest.push(arg);
    }
  }
  return { sql: rest.join(" "), json, db };
}
const QUERY_KEYWORDS = /^\s*(SELECT|WITH|EXPLAIN|SHOW|VALUES|TABLE)\b/i;
const RETURNING_CLAUSE = /\bRETURNING\b/i;
function classifySQL(sql) {
  if (QUERY_KEYWORDS.test(sql)) return "query";
  if (RETURNING_CLAUSE.test(sql)) return "query";
  return "exec";
}
async function runPgCommand(args, _ctx, _vfs) {
  const parsed = parsePgArgs(args);
  if (!parsed.sql) {
    return err(`Usage: pg "SQL statement"

Examples:
  pg "SELECT * FROM todos"
  pg "INSERT INTO todos (title) VALUES ('Buy milk')"
  pg --json "SELECT * FROM todos"
  pg --db myapp "SELECT count(*) FROM users"
  pg "\\dt"   (list tables)
  pg "\\d todos"  (describe table)`);
  }
  const { sql, json: jsonOutput, db } = parsed;
  try {
    if (sql === "\\dt" || sql === "dt") {
      const { handleDatabaseRequest: handleDatabaseRequest2 } = await import("./pglite-database-DKRVlYOI.js");
      const result2 = await handleDatabaseRequest2("tables", {}, db);
      if (result2.statusCode !== 200) return err(result2.body);
      const data = JSON.parse(result2.body);
      if (!data.tables || data.tables.length === 0) return ok("(no tables)");
      if (jsonOutput) return ok(JSON.stringify(data.tables));
      return ok(data.tables.join("\n"));
    }
    if (sql.startsWith("\\d ") || sql.startsWith("d ") && !QUERY_KEYWORDS.test(sql)) {
      const table = sql.replace(/^\\?d\s+/, "").trim();
      if (!table) return err('Usage: pg "\\d <table>"');
      const { handleDatabaseRequest: handleDatabaseRequest2 } = await import("./pglite-database-DKRVlYOI.js");
      const result2 = await handleDatabaseRequest2(`schema/${table}`, {}, db);
      if (result2.statusCode !== 200) return err(result2.body);
      const data = JSON.parse(result2.body);
      if (!data.columns || data.columns.length === 0) return ok(`Table "${table}" not found or has no columns`);
      if (jsonOutput) return ok(JSON.stringify(data.columns));
      return ok(formatTable(data.columns));
    }
    if (sql === "\\l" || sql === "l") {
      const { listDatabases, getActiveDatabase } = await import("./db-manager-DadVjJc9.js");
      const dbs = listDatabases();
      const active = getActiveDatabase();
      if (dbs.length === 0) return ok("(no databases)");
      if (jsonOutput) return ok(JSON.stringify(dbs));
      return ok(dbs.map((d) => `${d.name === active ? "* " : "  "}${d.name} (created ${d.createdAt})`).join("\n"));
    }
    const operation = classifySQL(sql);
    const { handleDatabaseRequest } = await import("./pglite-database-DKRVlYOI.js");
    const result = await handleDatabaseRequest(operation, { sql }, db);
    if (result.statusCode !== 200) return err(result.body);
    if (operation === "query") {
      const data = JSON.parse(result.body);
      if (jsonOutput) return ok(JSON.stringify(data.rows));
      if (!data.rows || data.rows.length === 0) return ok("(no rows)");
      return ok(formatTable(data.rows));
    }
    return ok("OK");
  } catch (error) {
    return err(error.message || String(error));
  }
}
export {
  classifySQL,
  parsePgArgs,
  runPgCommand
};
//# sourceMappingURL=pg-command-ibDMUuNa.js.map
