#!/usr/bin/env node
'use strict';

const path = require('path');

const brain = require(path.resolve(__dirname, '..', '..', '..', 'brain'));
const CtmAdapter = require(path.resolve(__dirname, '..', '..', '..', 'adapters', 'ctm'));
const ingest = require(path.resolve(__dirname, '..', '..', '..', 'loops', 'ingest'));

const standalone = require.main === module;

function ensureDb() {
  try {
    brain.getDb();
  } catch {
    brain.initDb();
  }
}

async function main() {
  ensureDb();
  const adapter = new CtmAdapter();
  const result = await ingest.runOnce([adapter]);
  const checkpoint = brain.getCheckpoint(ingest.checkpointName(adapter));
  const output = {
    ok: true,
    messagesIngested: result.memoriesIngested || 0,
    memoriesIngested: result.memoriesIngested || 0,
    checkpoint: checkpoint?.last_memory_at || null,
  };
  console.log(JSON.stringify(output));
  if (standalone) brain.closeDb();
  return output;
}

module.exports = { run: main };

if (require.main === module) {
  main().catch((err) => {
    console.error(JSON.stringify({ ok: false, error: err.message }));
    process.exit(1);
  });
}
