import "../../shared/src/dotenv.js";
import { LogContext, consoleLogSink } from "@rocicorp/logger";
import { astToZQL } from "../../ast-to-zql/src/ast-to-zql.js";
import { formatOutput } from "../../ast-to-zql/src/format.js";
import { must } from "../../shared/src/must.js";
import { parseOptions } from "../../shared/src/options.js";
import "../../shared/src/valita.js";
import { transformAndHashQuery } from "../../zero-cache/src/auth/read-authorizer.js";
import { ZERO_ENV_VAR_PREFIX, shardOptions, appOptions } from "../../zero-cache/src/config/zero-config.js";
import { loadSchemaAndPermissions } from "../../zero-cache/src/scripts/permissions.js";
import { pgClient } from "../../zero-cache/src/types/pg.js";
import { upstreamSchema, getShardID } from "../../zero-cache/src/types/shards.js";
import { string } from "@badrap/valita";
const options = {
  cvr: { db: string() },
  schema: {
    type: string().default("./schema.ts"),
    desc: ["Path to the schema file."]
  },
  app: appOptions,
  shard: shardOptions,
  hash: {
    type: string().optional(),
    desc: ["Hash of the query to fetch the AST for."]
  }
};
const config = parseOptions(options, { envNamePrefix: ZERO_ENV_VAR_PREFIX });
const lc = new LogContext("debug", {}, consoleLogSink);
const { permissions } = await loadSchemaAndPermissions(config.schema);
const cvrDB = pgClient(lc, config.cvr.db);
const rows = await cvrDB`select "clientAST", "internal" from ${cvrDB(upstreamSchema(getShardID(config)) + "/cvr")}."queries" where "queryHash" = ${must(
  config.hash
)} limit 1;`;
const queryAst = transformAndHashQuery(
  lc,
  "",
  rows[0].clientAST,
  permissions,
  {
    decoded: {}
  },
  rows[0].internal
).transformedAst;
console.log("\n=== AST ===\n");
console.log(JSON.stringify(queryAst, null, 2));
console.log("\n=== ZQL ===\n");
console.log(await formatOutput(queryAst.table + astToZQL(queryAst)));
await cvrDB.end();
//# sourceMappingURL=bin-transform.js.map
