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

const {
  handlePrecompact,
  handleSessionStart,
  handleStop,
  runLockedIngest,
} = require('./session-memory');

async function main(argv = process.argv.slice(2), stdin = process.stdin) {
  const command = argv[0] || '';
  const opts = parseArgs(argv.slice(1));

  if (command === 'ingest-file') {
    const result = await runLockedIngest({
      adapterId: opts.adapter,
      uri: opts.file,
      sourceFile: opts.file,
      sourceId: opts.sourceId || undefined,
      cwd: opts.cwd || '',
    });
    writeJson(result);
    return result;
  }

  const data = await readStdinJson(stdin);
  const harness = opts.harness || 'walle';
  let result;
  if (command === 'session-start') {
    result = await handleSessionStart(data, { harness });
  } else if (command === 'stop') {
    result = await handleStop(data, { harness, background: opts.background !== 'false' });
  } else if (command === 'precompact') {
    result = await handlePrecompact(data, { harness });
  } else {
    throw new Error(`Unknown hook command: ${command}`);
  }
  writeJson(result);
  return result;
}

function parseArgs(argv) {
  const opts = {};
  for (let i = 0; i < argv.length; i++) {
    const arg = argv[i];
    if (!arg.startsWith('--')) continue;
    const key = arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
    const next = argv[i + 1];
    if (!next || next.startsWith('--')) {
      opts[key] = 'true';
    } else {
      opts[key] = next;
      i += 1;
    }
  }
  return opts;
}

function readStdinJson(stdin) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    stdin.on('data', (chunk) => chunks.push(chunk));
    stdin.on('error', reject);
    stdin.on('end', () => {
      const text = Buffer.concat(chunks).toString('utf8').trim();
      if (!text) return resolve({});
      try {
        resolve(JSON.parse(text));
      } catch (err) {
        reject(new Error(`Invalid hook JSON: ${err.message}`));
      }
    });
  });
}

function writeJson(result) {
  process.stdout.write(`${JSON.stringify(result)}\n`);
}

if (require.main === module) {
  main().catch((err) => {
    process.stderr.write(`[wall-e-hook] ${err.message}\n`);
    process.exitCode = 1;
  });
}

module.exports = {
  main,
  parseArgs,
  readStdinJson,
};
