import { runMigrations } from '../../engines/schema/migrate.js';
export const SYNAPSE_SCHEMA = `
CREATE TABLE IF NOT EXISTS synapse_operatives (
  id                 TEXT PRIMARY KEY,
  name               TEXT NOT NULL UNIQUE,
  role_title         TEXT,
  reports_to_operative_id TEXT,
  skill_id           TEXT,
  specialist_id      TEXT,
  origin             TEXT NOT NULL DEFAULT 'mandate'
    CHECK(origin IN ('mandate','manual','approval','system')),
  state              TEXT NOT NULL DEFAULT 'IDLE'
    CHECK(state IN ('IDLE','ACTIVE','CHECKOUT','STANDDOWN','SUSPENDED','DONE')),
  suspend_reason     TEXT
    CHECK(suspend_reason IN ('budget_exceeded','compaction','manual') OR suspend_reason IS NULL),
  termination_reason TEXT,
  health_state       TEXT NOT NULL DEFAULT 'IDLE'
    CHECK(health_state IN ('WORKING','STALLED','ZOMBIE','BLOCKED','IDLE')),
  mission_id         TEXT,
  strike_team_id     TEXT,
  budget_cap_usd     REAL NOT NULL DEFAULT 10.0,
  budget_scope       TEXT NOT NULL DEFAULT 'operative'
    CHECK(budget_scope IN ('operative','mission','crew','project')),
  budget_scope_id    TEXT,
  spent_usd          REAL NOT NULL DEFAULT 0.0,
  commendation_score REAL NOT NULL DEFAULT 0.0,
  sortie_interval_ms INTEGER NOT NULL DEFAULT 30000,
  last_sortie_at     TEXT,
  created_at         TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS synapse_strike_teams (
  id            TEXT PRIMARY KEY,
  mandate_text  TEXT NOT NULL,
  operative_ids TEXT NOT NULL DEFAULT '[]',
  mission_ids   TEXT NOT NULL DEFAULT '[]',
  blueprint_id  TEXT,
  status        TEXT NOT NULL DEFAULT 'deploying'
    CHECK(status IN ('deploying','active','converging','done','standdown')),
  created_at    TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS synapse_missions (
  id                     TEXT PRIMARY KEY,
  parent_mission_id      TEXT,
  ancestry_path          TEXT NOT NULL DEFAULT '[]',
  correlation_id         TEXT,
  strike_team_id         TEXT,
  title                  TEXT NOT NULL,
  complexity             TEXT NOT NULL DEFAULT 'orchestrate'
    CHECK(complexity IN ('read','orchestrate','mutate')),
  status                 TEXT NOT NULL DEFAULT 'open'
    CHECK(status IN ('open','active','done','blocked','failed')),
  assigned_operative_id  TEXT,
  requires_approval_gate INTEGER NOT NULL DEFAULT 0,
  approval_scope         TEXT NOT NULL DEFAULT 'mission'
    CHECK(approval_scope IN ('operative','mission','crew','project')),
  approval_scope_id      TEXT,
  budget_scope           TEXT NOT NULL DEFAULT 'mission'
    CHECK(budget_scope IN ('operative','mission','crew','project')),
  budget_scope_id        TEXT,
  created_at             TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS synapse_sorties (
  id              TEXT PRIMARY KEY,
  operative_id    TEXT NOT NULL,
  mission_id      TEXT,
  status          TEXT NOT NULL DEFAULT 'running'
    CHECK(status IN ('running','completed','failed','interrupted_compaction','deferred')),
  tokens_used     INTEGER NOT NULL DEFAULT 0,
  cost_usd        REAL NOT NULL DEFAULT 0.0,
  field_report_id TEXT,
  started_at      TEXT NOT NULL DEFAULT (datetime('now')),
  completed_at    TEXT
);

CREATE TABLE IF NOT EXISTS synapse_field_reports (
  id                       TEXT PRIMARY KEY,
  sortie_id                TEXT NOT NULL,
  operative_id             TEXT NOT NULL,
  strike_team_id           TEXT,
  mission_title            TEXT NOT NULL,
  findings                 TEXT NOT NULL DEFAULT '',
  files_changed            TEXT NOT NULL DEFAULT '[]',
  blockers_encountered     TEXT NOT NULL DEFAULT '',
  next_recommended_action  TEXT NOT NULL DEFAULT '',
  tokens_used              INTEGER NOT NULL DEFAULT 0,
  cost_usd                 REAL NOT NULL DEFAULT 0.0,
  ledger_path              TEXT,
  status                   TEXT NOT NULL DEFAULT 'completed'
    CHECK(status IN ('completed','blocked','failed')),
  completed_at             TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS synapse_approvals (
  id            TEXT PRIMARY KEY,
  mission_id    TEXT,
  operative_id  TEXT NOT NULL,
  scope         TEXT NOT NULL DEFAULT 'mission'
    CHECK(scope IN ('operative','mission','crew','project')),
  scope_id      TEXT,
  action        TEXT NOT NULL,
  description   TEXT NOT NULL,
  payload_json  TEXT NOT NULL DEFAULT '{}',
  status        TEXT NOT NULL DEFAULT 'pending'
    CHECK(status IN ('pending','approved','rejected')),
  decided_at    TEXT,
  created_at    TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_syn_operatives_state  ON synapse_operatives(state);
CREATE INDEX IF NOT EXISTS idx_syn_operatives_team   ON synapse_operatives(strike_team_id);
CREATE INDEX IF NOT EXISTS idx_syn_sorties_op_status ON synapse_sorties(operative_id, status);
CREATE INDEX IF NOT EXISTS idx_syn_sorties_mission_status ON synapse_sorties(mission_id, status);
CREATE INDEX IF NOT EXISTS idx_syn_field_reports_sortie ON synapse_field_reports(sortie_id);
CREATE INDEX IF NOT EXISTS idx_syn_missions_team     ON synapse_missions(strike_team_id);
CREATE INDEX IF NOT EXISTS idx_syn_approvals_pending ON synapse_approvals(status);
`;
function hasColumn(db, table, column) {
    const rows = db.prepare(`PRAGMA table_info(${table})`).all();
    return rows.some((row) => row.name === column);
}
function addColumnIfMissing(db, table, column, ddl) {
    if (hasColumn(db, table, column))
        return;
    db.prepare(ddl).run();
}
export function initSynapseSchema(db) {
    // File-based forward-only migrations (PRAGMA user_version scheme).
    runMigrations(db, 'synapse');
    db.exec(SYNAPSE_SCHEMA);
    addColumnIfMissing(db, 'synapse_operatives', 'role_title', 'ALTER TABLE synapse_operatives ADD COLUMN role_title TEXT');
    addColumnIfMissing(db, 'synapse_operatives', 'reports_to_operative_id', 'ALTER TABLE synapse_operatives ADD COLUMN reports_to_operative_id TEXT');
    addColumnIfMissing(db, 'synapse_operatives', 'origin', "ALTER TABLE synapse_operatives ADD COLUMN origin TEXT NOT NULL DEFAULT 'mandate'");
    addColumnIfMissing(db, 'synapse_operatives', 'budget_scope', "ALTER TABLE synapse_operatives ADD COLUMN budget_scope TEXT NOT NULL DEFAULT 'operative'");
    addColumnIfMissing(db, 'synapse_operatives', 'budget_scope_id', 'ALTER TABLE synapse_operatives ADD COLUMN budget_scope_id TEXT');
    addColumnIfMissing(db, 'synapse_operatives', 'termination_reason', 'ALTER TABLE synapse_operatives ADD COLUMN termination_reason TEXT');
    addColumnIfMissing(db, 'synapse_operatives', 'company_id', "ALTER TABLE synapse_operatives ADD COLUMN company_id TEXT NOT NULL DEFAULT 'default'");
    addColumnIfMissing(db, 'synapse_missions', 'company_id', "ALTER TABLE synapse_missions ADD COLUMN company_id TEXT NOT NULL DEFAULT 'default'");
    addColumnIfMissing(db, 'synapse_sorties', 'company_id', "ALTER TABLE synapse_sorties ADD COLUMN company_id TEXT NOT NULL DEFAULT 'default'");
    addColumnIfMissing(db, 'synapse_missions', 'ancestry_path', "ALTER TABLE synapse_missions ADD COLUMN ancestry_path TEXT NOT NULL DEFAULT '[]'");
    addColumnIfMissing(db, 'synapse_missions', 'correlation_id', 'ALTER TABLE synapse_missions ADD COLUMN correlation_id TEXT');
    addColumnIfMissing(db, 'synapse_missions', 'approval_scope', "ALTER TABLE synapse_missions ADD COLUMN approval_scope TEXT NOT NULL DEFAULT 'mission'");
    addColumnIfMissing(db, 'synapse_missions', 'approval_scope_id', 'ALTER TABLE synapse_missions ADD COLUMN approval_scope_id TEXT');
    addColumnIfMissing(db, 'synapse_missions', 'budget_scope', "ALTER TABLE synapse_missions ADD COLUMN budget_scope TEXT NOT NULL DEFAULT 'mission'");
    addColumnIfMissing(db, 'synapse_missions', 'budget_scope_id', 'ALTER TABLE synapse_missions ADD COLUMN budget_scope_id TEXT');
    addColumnIfMissing(db, 'synapse_approvals', 'scope', "ALTER TABLE synapse_approvals ADD COLUMN scope TEXT NOT NULL DEFAULT 'mission'");
    addColumnIfMissing(db, 'synapse_approvals', 'scope_id', 'ALTER TABLE synapse_approvals ADD COLUMN scope_id TEXT');
    addColumnIfMissing(db, 'synapse_approvals', 'payload_json', "ALTER TABLE synapse_approvals ADD COLUMN payload_json TEXT NOT NULL DEFAULT '{}'");
    db.exec('CREATE INDEX IF NOT EXISTS idx_syn_missions_corr ON synapse_missions(correlation_id, parent_mission_id)');
    db.exec('CREATE INDEX IF NOT EXISTS idx_syn_approvals_scope ON synapse_approvals(scope, scope_id, mission_id, status)');
    db.prepare(`
    UPDATE synapse_operatives
    SET budget_scope = COALESCE(NULLIF(budget_scope, ''), 'operative'),
        budget_scope_id = COALESCE(budget_scope_id, id),
        origin = COALESCE(NULLIF(origin, ''), 'mandate')
  `).run();
    db.prepare(`
    UPDATE synapse_missions
    SET ancestry_path = CASE
      WHEN ancestry_path IS NULL OR ancestry_path = '' THEN printf('["%s"]', id)
      ELSE ancestry_path
    END,
    correlation_id = COALESCE(correlation_id, parent_mission_id, id),
    approval_scope = COALESCE(NULLIF(approval_scope, ''), 'mission'),
    approval_scope_id = COALESCE(approval_scope_id, id),
    budget_scope = COALESCE(NULLIF(budget_scope, ''), 'mission'),
    budget_scope_id = COALESCE(budget_scope_id, strike_team_id, id)
  `).run();
    db.prepare(`
    UPDATE synapse_approvals
    SET scope = COALESCE(NULLIF(scope, ''), 'mission'),
        scope_id = COALESCE(scope_id, mission_id)
  `).run();
}
