import {
  logger
} from "./chunk-K44MW7JJ.js";

// src/server/db/index.ts
import Database from "better-sqlite3";
var db = null;
function initDatabase(config) {
  if (db) {
    return db;
  }
  logger.info("Initializing database", { path: config.database.path });
  db = new Database(config.database.path);
  db.pragma("journal_mode = WAL");
  db.pragma("foreign_keys = ON");
  runMigrations(db);
  const result = db.prepare(`UPDATE sessions SET is_running = 0 WHERE is_running = 1`).run();
  if (result.changes > 0) {
    logger.info("Reset stale running states", { count: result.changes });
  }
  const freelistCount = db.pragma("freelist_count", { simple: true });
  if (freelistCount > 1e4) {
    logger.info("Vacuuming database", { freelistCount });
    db.exec("VACUUM");
    logger.info("Database vacuumed");
  }
  return db;
}
function getDatabase() {
  if (!db) {
    throw new Error("Database not initialized. Call initDatabase first.");
  }
  return db;
}
function runMigrations(db2) {
  logger.info("Running database migrations");
  db2.exec(`
    CREATE TABLE IF NOT EXISTS projects (
      id TEXT PRIMARY KEY,
      name TEXT NOT NULL,
      workdir TEXT NOT NULL UNIQUE,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL
    )
  `);
  db2.exec(`
    CREATE TABLE IF NOT EXISTS sessions (
      id TEXT PRIMARY KEY,
      project_id TEXT NOT NULL,
      workdir TEXT NOT NULL,
      phase TEXT NOT NULL DEFAULT 'idle',
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      title TEXT,
      total_tokens_used INTEGER DEFAULT 0,
      total_tool_calls INTEGER DEFAULT 0,
      iteration_count INTEGER DEFAULT 0,
      FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
    )
  `);
  db2.exec(`
    CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project_id)
  `);
  const columns = db2.prepare(`PRAGMA table_info(sessions)`).all();
  const columnNames = columns.map((c) => c.name);
  if (!columnNames.includes("mode")) {
    logger.info("Migrating sessions table: adding mode column");
    db2.exec(`ALTER TABLE sessions ADD COLUMN mode TEXT NOT NULL DEFAULT 'planner'`);
    db2.exec(`
      UPDATE sessions SET mode = CASE
        WHEN phase = 'idle' THEN 'planner'
        WHEN phase = 'planning' THEN 'planner'
        WHEN phase = 'executing' THEN 'builder'
        WHEN phase = 'validating' THEN 'verifier'
        WHEN phase = 'completed' THEN 'planner'
        ELSE 'planner'
      END
    `);
  }
  if (!columnNames.includes("is_running")) {
    logger.info("Migrating sessions table: adding is_running column");
    db2.exec(`ALTER TABLE sessions ADD COLUMN is_running INTEGER NOT NULL DEFAULT 0`);
  }
  if (!columnNames.includes("workflow_phase")) {
    logger.info("Migrating sessions table: adding workflow_phase column");
    db2.exec(`ALTER TABLE sessions ADD COLUMN workflow_phase TEXT NOT NULL DEFAULT 'plan'`);
  }
  if (!columnNames.includes("danger_level")) {
    logger.info("Migrating sessions table: adding danger_level column");
    db2.exec(`ALTER TABLE sessions ADD COLUMN danger_level TEXT NOT NULL DEFAULT 'normal'`);
  }
  db2.exec(`
    CREATE TABLE IF NOT EXISTS settings (
      key TEXT PRIMARY KEY,
      value TEXT NOT NULL,
      updated_at TEXT NOT NULL
    )
  `);
  const projectColumns = db2.prepare(`PRAGMA table_info(projects)`).all();
  const projectColumnNames = projectColumns.map((c) => c.name);
  if (!projectColumnNames.includes("custom_instructions")) {
    logger.info("Migrating projects table: adding custom_instructions column");
    db2.exec(`ALTER TABLE projects ADD COLUMN custom_instructions TEXT`);
  }
  if (!projectColumnNames.includes("danger_level")) {
    logger.info("Migrating projects table: adding danger_level column");
    db2.exec(`ALTER TABLE projects ADD COLUMN danger_level TEXT`);
  }
  if (!projectColumnNames.includes("is_starred")) {
    logger.info("Migrating projects table: adding is_starred column");
    db2.exec(`ALTER TABLE projects ADD COLUMN is_starred INTEGER NOT NULL DEFAULT 0`);
  }
  db2.exec(`
    CREATE TABLE IF NOT EXISTS events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      session_id TEXT NOT NULL,
      seq INTEGER NOT NULL,
      timestamp INTEGER NOT NULL,
      event_type TEXT NOT NULL,
      payload TEXT NOT NULL,
      UNIQUE(session_id, seq),
      FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
    )
  `);
  db2.exec(`
    CREATE INDEX IF NOT EXISTS idx_events_session_seq ON events(session_id, seq)
  `);
  db2.exec(`
    CREATE INDEX IF NOT EXISTS idx_events_session_type ON events(session_id, event_type)
  `);
  if (!columnNames.includes("provider_id")) {
    logger.info("Migrating sessions table: adding provider_id column");
    db2.exec(`ALTER TABLE sessions ADD COLUMN provider_id TEXT`);
  }
  if (!columnNames.includes("provider_model")) {
    logger.info("Migrating sessions table: adding provider_model column");
    db2.exec(`ALTER TABLE sessions ADD COLUMN provider_model TEXT`);
  }
  if (!columnNames.includes("message_count")) {
    logger.info("Migrating sessions table: adding message_count column");
    db2.exec(`ALTER TABLE sessions ADD COLUMN message_count INTEGER NOT NULL DEFAULT 0`);
    logger.info("Backfilling message counts");
    const backfillResult = db2.prepare(
      `
      UPDATE sessions 
      SET message_count = (
        SELECT COALESCE(
          -- First try: get count from latest snapshot
          (SELECT json_array_length(json_extract(
            (SELECT payload FROM events WHERE session_id = sessions.id AND event_type = 'turn.snapshot' ORDER BY seq DESC LIMIT 1),
            '$.messages'
          ))),
          -- Fallback: count message.start events for user/assistant roles
          (SELECT COUNT(*) FROM events e 
           WHERE e.session_id = sessions.id 
           AND e.event_type = 'message.start'
           AND json_extract(e.payload, '$.role') IN ('user', 'assistant'))
        )
      )
    `
    ).run();
    logger.info("Backfilled message counts", { count: backfillResult.changes });
  }
  logger.info("Database migrations completed");
}

export {
  initDatabase,
  getDatabase
};
//# sourceMappingURL=chunk-FBGWG4N6.js.map