import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';

function resolveUpdaterScript(): string | null {
  const candidates = [
    join(homedir(), '.agents', 'skills', 'kespace-openclaw', 'scripts', 'ks-updater.mjs'),
    join(homedir(), '.agents', 'skills', 'kespace', 'scripts', 'ks-updater.mjs'),
    join(homedir(), '.agents', 'skills', 'ks-openclaw', 'scripts', 'ks-updater.mjs'),
    join(homedir(), '.agents', 'skills', 'ks', 'scripts', 'ks-updater.mjs'),
  ];
  for (const candidate of candidates) {
    if (existsSync(candidate)) return candidate;
  }
  return null;
}

function shouldRun(event: { type?: string; action?: string }): boolean {
  if (event.type === 'agent' && event.action === 'bootstrap') return true;
  if (event.type === 'command' && (event.action === 'new' || event.action === 'reset')) {
    return true;
  }
  return false;
}

export default async function handler(event: { type?: string; action?: string }) {
  if (!shouldRun(event)) return;
  const script = resolveUpdaterScript();
  if (!script) return;
  const node = process.platform === 'win32' ? 'node.exe' : 'node';
  const child = spawn(node, [script, '--quiet', '--trigger=session-start'], {
    detached: true,
    stdio: 'ignore',
  });
  child.unref();
}
