import { MemoryStorage } from "../../../zql/src/ivm/memory-storage.js";
import { AccumulatorDebugger, serializePlanDebugEvents } from "../../../zql/src/planner/planner-debug.js";
import { Database } from "../../../zqlite/src/db.js";
import { TableSource } from "../../../zqlite/src/table-source.js";
import { Debug } from "../../../zql/src/builder/debug-delegate.js";
import { computeZqlSpecs, mustGetTableSpec } from "../db/lite-tables.js";
import { createSQLiteCostModel } from "../../../zqlite/src/sqlite-cost-model.js";
import { runAst } from "./run-ast.js";
import { explainQueries } from "../../../zqlite/src/explain-queries.js";
import { _usingCtx } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/usingCtx.js";
import { TimeSliceTimer } from "./view-syncer/view-syncer.js";
//#region ../zero-cache/src/services/analyze.ts
var TIME_SLICE_LAP_THRESHOLD_MS = 200;
async function analyzeQuery(lc, config, clientSchema, ast, syncedRows = true, vendedRows = false, permissions, auth, joinPlans = false) {
	try {
		var _usingCtx$1 = _usingCtx();
		const db = _usingCtx$1.u(new Database(lc, config.replica.file));
		const fullTables = /* @__PURE__ */ new Map();
		const tableSpecs = /* @__PURE__ */ new Map();
		const tables = /* @__PURE__ */ new Map();
		computeZqlSpecs(lc, db, { includeBackfillingColumns: false }, tableSpecs, fullTables);
		const planDebugger = joinPlans ? new AccumulatorDebugger() : void 0;
		const costModel = joinPlans ? createSQLiteCostModel(db, tableSpecs) : void 0;
		const timer = await new TimeSliceTimer(lc).start();
		const shouldYield = () => timer.elapsedLap() > TIME_SLICE_LAP_THRESHOLD_MS;
		const yieldProcess = () => timer.yieldProcess();
		const result = await runAst(lc, clientSchema, ast, true, {
			applyPermissions: permissions !== void 0,
			syncedRows,
			vendedRows,
			auth,
			db,
			tableSpecs,
			permissions,
			costModel,
			planDebugger,
			host: {
				debug: new Debug(),
				getSource(tableName) {
					let source = tables.get(tableName);
					if (source) return source;
					const tableSpec = mustGetTableSpec(tableSpecs, tableName);
					const { primaryKey } = tableSpec.tableSpec;
					source = new TableSource(lc, config.log, db, tableName, tableSpec.zqlSpec, primaryKey, shouldYield);
					tables.set(tableName, source);
					return source;
				},
				createStorage() {
					return new MemoryStorage();
				},
				decorateSourceInput: (input) => input,
				decorateInput: (input) => input,
				addEdge() {},
				decorateFilterInput: (input) => input
			}
		}, yieldProcess);
		result.sqlitePlans = explainQueries(result.readRowCountsByQuery ?? {}, db);
		if (planDebugger) result.joinPlans = serializePlanDebugEvents(planDebugger.events);
		return result;
	} catch (_) {
		_usingCtx$1.e = _;
	} finally {
		_usingCtx$1.d();
	}
}
//#endregion
export { analyzeQuery };

//# sourceMappingURL=analyze.js.map