import {
  init_migrations,
  runMigrations
} from "./chunk-KBM3MISV.js";
import {
  __esm
} from "./chunk-2ESYSVXG.js";

// src/db/client.ts
import Database from "libsql";
import path from "path";
import fs from "fs";
function resolveDbPath() {
  const p = process.env.DATABASE_PATH || "./data/managed-agents.db";
  return path.isAbsolute(p) ? p : path.join(
    /* turbopackIgnore: true */
    process.cwd(),
    p
  );
}
function getDb() {
  if (g.__caDb) return g.__caDb;
  const dbPath = resolveDbPath();
  const dir = path.dirname(dbPath);
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  const tursoUrl = process.env.TURSO_URL;
  const tursoToken = process.env.TURSO_AUTH_TOKEN;
  const db = tursoUrl ? new Database(dbPath, { syncUrl: tursoUrl, authToken: tursoToken }) : new Database(dbPath);
  db.pragma("journal_mode = WAL");
  db.pragma("synchronous = NORMAL");
  db.pragma("foreign_keys = ON");
  db.pragma("busy_timeout = 5000");
  runMigrations(db);
  if (tursoUrl) {
    try {
      db.sync();
    } catch {
    }
  }
  g.__caDb = db;
  g.__caDbPath = dbPath;
  return db;
}
function syncDb() {
  if (!g.__caDb || !process.env.TURSO_URL) return;
  try {
    g.__caDb.sync();
  } catch (err) {
    console.warn("[db] sync failed:", err);
  }
}
function closeDb() {
  if (g.__caDb) {
    g.__caDb.close();
    g.__caDb = void 0;
  }
}
var g;
var init_client = __esm({
  "src/db/client.ts"() {
    init_migrations();
    g = globalThis;
  }
});

export {
  getDb,
  syncDb,
  closeDb,
  init_client
};
