// engine/db/migrations/011-remaining-state.js
//
// Phase 9.2: finish the JSON→SQL migration. Four remaining engine state
// files move into their own tables; the JSON files are kept as dual-write
// mirrors for back-compat.
//
//   engine/cooldowns.json        -> cooldowns
//   engine/pending-rebases.json  -> pending_rebases
//   engine/cc-sessions.json      -> cc_sessions
//   engine/doc-sessions.json     -> doc_sessions

const path = require('path');
const fs = require('fs');

function _resolveMinionsDir() {
  const envHome = process.env.MINIONS_HOME || process.env.MINIONS_TEST_DIR;
  if (envHome) return envHome;
  try { return require('../../shared').MINIONS_DIR; } catch { return null; }
}

function _readJsonOr(filePath, fallback) {
  try {
    const raw = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(raw);
  } catch { return fallback; }
}

module.exports = {
  version: 11,
  description: 'cooldowns + pending_rebases + cc_sessions + doc_sessions',
  up(db) {
    db.exec(`
      CREATE TABLE cooldowns (
        key         TEXT PRIMARY KEY,
        data        TEXT NOT NULL,
        updated_at  INTEGER NOT NULL
      );

      CREATE TABLE pending_rebases (
        seq         INTEGER PRIMARY KEY AUTOINCREMENT,
        data        TEXT NOT NULL,
        updated_at  INTEGER NOT NULL
      );

      CREATE TABLE cc_sessions (
        id          TEXT PRIMARY KEY,
        data        TEXT NOT NULL,
        updated_at  INTEGER NOT NULL
      );

      CREATE TABLE doc_sessions (
        key         TEXT PRIMARY KEY,
        data        TEXT NOT NULL,
        updated_at  INTEGER NOT NULL
      );
    `);

    const minionsDir = _resolveMinionsDir();
    if (!minionsDir) return;
    const now = Date.now();
    let inserted = 0;

    // ── cooldowns ──────────────────────────────────────────────────────────
    {
      const raw = _readJsonOr(path.join(minionsDir, 'engine', 'cooldowns.json'), null);
      if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
        const ins = db.prepare(`INSERT INTO cooldowns (key, data, updated_at) VALUES (?, ?, ?)`);
        for (const [k, v] of Object.entries(raw)) {
          try { ins.run(String(k), JSON.stringify(v), now); inserted += 1; }
          catch { /* duplicate / corrupt — skip */ }
        }
      }
    }

    // ── pending_rebases ────────────────────────────────────────────────────
    {
      const raw = _readJsonOr(path.join(minionsDir, 'engine', 'pending-rebases.json'), null);
      if (Array.isArray(raw)) {
        const ins = db.prepare(`INSERT INTO pending_rebases (data, updated_at) VALUES (?, ?)`);
        for (const entry of raw) {
          if (!entry || typeof entry !== 'object') continue;
          try { ins.run(JSON.stringify(entry), now); inserted += 1; }
          catch { /* corrupt — skip */ }
        }
      }
    }

    // ── cc_sessions ────────────────────────────────────────────────────────
    {
      const raw = _readJsonOr(path.join(minionsDir, 'engine', 'cc-sessions.json'), null);
      if (Array.isArray(raw)) {
        const ins = db.prepare(`INSERT INTO cc_sessions (id, data, updated_at) VALUES (?, ?, ?)`);
        for (const entry of raw) {
          if (!entry || typeof entry !== 'object' || !entry.id) continue;
          try { ins.run(String(entry.id), JSON.stringify(entry), now); inserted += 1; }
          catch { /* duplicate id — skip */ }
        }
      }
    }

    // ── doc_sessions ───────────────────────────────────────────────────────
    {
      const raw = _readJsonOr(path.join(minionsDir, 'engine', 'doc-sessions.json'), null);
      if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
        const ins = db.prepare(`INSERT INTO doc_sessions (key, data, updated_at) VALUES (?, ?, ?)`);
        for (const [k, v] of Object.entries(raw)) {
          try { ins.run(String(k), JSON.stringify(v), now); inserted += 1; }
          catch { /* duplicate / corrupt — skip */ }
        }
      }
    }

    // eslint-disable-next-line no-console
    console.log(`[db-migrate] v11: backfilled ${inserted} small-state rows; JSON files kept as dual-write mirrors`);
  },
};
