import path from 'path';
import fs from 'fs';
import os from 'os';
import initSqlJs from 'sql.js';
import { drizzle } from 'drizzle-orm/sql-js';
import { windows } from '../schema.js';
// Database location: ~/.config/shella/ (both dev and prod)
const CONFIG_DIR = path.join(os.homedir(), '.config', 'shella');
const STATE_DIR = CONFIG_DIR;
const DB_FILE = path.join(STATE_DIR, 'shella.db');
// Singleton database instance
let db = null;
let sqlite = null;
// Persistence interval (5 seconds)
const SAVE_INTERVAL_MS = 5000;
let saveInterval = null;
function ensureStateDir() {
    if (!fs.existsSync(STATE_DIR)) {
        fs.mkdirSync(STATE_DIR, { recursive: true });
    }
}
/**
 * Save the in-memory database to disk.
 * sql.js is in-memory, so we need to manually persist.
 */
function saveDatabase() {
    if (!sqlite)
        return;
    try {
        const data = sqlite.export();
        fs.writeFileSync(DB_FILE, Buffer.from(data));
    }
    catch (err) {
        console.error('[database] Failed to save:', err);
    }
}
/**
 * Set up periodic saves and exit handlers
 */
function setupPersistence() {
    // Periodic save every 5 seconds
    saveInterval = setInterval(saveDatabase, SAVE_INTERVAL_MS);
    // Save on exit
    const exitHandler = () => {
        console.log('[database] Saving before exit...');
        saveDatabase();
        if (saveInterval)
            clearInterval(saveInterval);
    };
    process.on('SIGINT', () => {
        exitHandler();
        process.exit();
    });
    process.on('SIGTERM', () => {
        exitHandler();
        process.exit();
    });
    process.on('exit', exitHandler);
}
async function initDatabase() {
    ensureStateDir();
    // Initialize sql.js (loads WebAssembly)
    const SQL = await initSqlJs();
    // Load existing database or create new one
    const fileBuffer = fs.existsSync(DB_FILE) ? fs.readFileSync(DB_FILE) : undefined;
    sqlite = new SQL.Database(fileBuffer);
    // Create table if not exists
    sqlite.run(`
    CREATE TABLE IF NOT EXISTS windows (
      id TEXT PRIMARY KEY,
      directory_id TEXT NOT NULL,
      root_session_id TEXT,
      active_session_id TEXT,
      last_active_at TEXT,
      agent TEXT,
      model_provider TEXT,
      model_id TEXT,
      label TEXT,
      created_at TEXT NOT NULL
    )
  `);
    // Set up periodic persistence
    setupPersistence();
    // Save immediately
    saveDatabase();
    return drizzle(sqlite, { schema: { windows } });
}
// Promise to track initialization
let initPromise = null;
export async function getDatabase() {
    if (!db) {
        if (!initPromise) {
            initPromise = initDatabase().then((database) => {
                db = database;
                console.log('[database] Initialized at', DB_FILE);
                return database;
            });
        }
        await initPromise;
    }
    return db;
}
// Synchronous getter for compatibility (throws if not initialized)
export function getDatabaseSync() {
    if (!db) {
        throw new Error('Database not initialized. Call getDatabase() first.');
    }
    return db;
}
export { STATE_DIR, CONFIG_DIR };
