/**
 * Explicit SQL migration runner for the local `transcript_memory.db` database.
 *
 * Instead of embedding ad-hoc ALTER TABLE statements inline in getDb(),
 * migrations are declared as ordered entries. Each entry has a unique ID
 * and one or more SQL statements. The runner:
 *
 *  1. Creates a `transcript_memory_migrations` metadata table (if needed).
 *  2. Applies any migration whose ID is not yet recorded.
 *  3. Records each successful migration.
 *
 * Call `runTranscriptMemoryMigrations(db)` once inside getDb(), after the
 * base `CREATE TABLE IF NOT EXISTS wake_cycles (…)` statement, but before
 * preparing any statements that depend on new columns.
 */
import { logger } from "../../logger.js";
/**
 * Ordered list of migrations. New migrations are appended at the end.
 * IDs must be unique and stable.
 */
const MIGRATIONS = [
    {
        id: "20260504_add_usage_reporting",
        description: "Add usage-reporting columns to wake_cycles",
        sql: [
            "ALTER TABLE wake_cycles ADD COLUMN tool_calls_json TEXT",
            "ALTER TABLE wake_cycles ADD COLUMN usage_reported INTEGER NOT NULL DEFAULT 0",
            "ALTER TABLE wake_cycles ADD COLUMN trigger_type TEXT",
            "ALTER TABLE wake_cycles ADD COLUMN trigger_channel TEXT",
            "ALTER TABLE wake_cycles ADD COLUMN outcome TEXT",
            "ALTER TABLE wake_cycles ADD COLUMN tool_call_count INTEGER NOT NULL DEFAULT 0",
            "ALTER TABLE wake_cycles ADD COLUMN tool_calls_truncated INTEGER NOT NULL DEFAULT 0",
            "ALTER TABLE wake_cycles ADD COLUMN reported_tool_call_count INTEGER",
            "ALTER TABLE wake_cycles ADD COLUMN usage_report_error TEXT",
            "ALTER TABLE wake_cycles ADD COLUMN usage_report_attempted_at TEXT",
            `CREATE INDEX IF NOT EXISTS idx_wake_cycles_usage_reported
        ON wake_cycles(usage_reported, timestamp_start)`,
        ],
    },
];
// ---------------------------------------------------------------------------
// Runner
// ---------------------------------------------------------------------------
/**
 * Run all pending transcript-memory migrations against the given database.
 *
 * Safe to call on every startup — already-applied migrations are skipped.
 * Each migration is wrapped in a transaction so partial failures are
 * rolled back cleanly (leaving the migration un-recorded).
 */
export function runTranscriptMemoryMigrations(db) {
    // Ensure the metadata table exists.
    db.exec(`
    CREATE TABLE IF NOT EXISTS transcript_memory_migrations (
      id TEXT PRIMARY KEY,
      applied_at TEXT NOT NULL
    )
  `);
    const stmtCheck = db.prepare("SELECT 1 FROM transcript_memory_migrations WHERE id = ?");
    const stmtRecord = db.prepare("INSERT INTO transcript_memory_migrations (id, applied_at) VALUES (?, ?)");
    for (const migration of MIGRATIONS) {
        const existing = stmtCheck.get(migration.id);
        if (existing)
            continue; // already applied
        try {
            db.exec("BEGIN");
            for (const sql of migration.sql) {
                db.exec(sql);
            }
            stmtRecord.run(migration.id, new Date().toISOString());
            db.exec("COMMIT");
            logger.system(`[transcript-memory-migrations] Applied: ${migration.id} — ${migration.description}`);
        }
        catch (err) {
            try {
                db.exec("ROLLBACK");
            }
            catch {
                // best-effort rollback
            }
            logger.warn(`[transcript-memory-migrations] Failed to apply ${migration.id}: ${err instanceof Error ? err.message : String(err)}`);
            // Stop processing further migrations — ordering matters.
            break;
        }
    }
}
//# sourceMappingURL=transcript-memory-migrations.js.map