import { describe, it, expect } from 'vitest';

function generateStartWrapper(
  nodePath: string,
  projectRoot: string,
  pidFile: string,
): string {
  return [
    '#!/bin/sh',
    'set -eu',
    `cd ${JSON.stringify(projectRoot)}`,
    `if [ -f ${JSON.stringify(pidFile)} ]; then`,
    `  OLD_PID=$(cat ${JSON.stringify(pidFile)} 2>/dev/null || true)`,
    '  if [ -n "${OLD_PID:-}" ] && kill -0 "$OLD_PID" 2>/dev/null; then',
    '    echo "Clawdie is already running" >&2',
    '    exit 1',
    '  fi',
    'fi',
    `nohup ${JSON.stringify(nodePath)} ${JSON.stringify(projectRoot + '/dist/index.js')} >> ${JSON.stringify(projectRoot + '/logs/clawdie.log')} 2>> ${JSON.stringify(projectRoot + '/logs/clawdie.error.log')} &`,
    `echo $! > ${JSON.stringify(pidFile)}`,
    'echo "Started Clawdie"',
    '',
  ].join('\n');
}

function generateStopWrapper(pidFile: string): string {
  return [
    '#!/bin/sh',
    'set -eu',
    `if [ ! -f ${JSON.stringify(pidFile)} ]; then`,
    '  echo "No PID file found" >&2',
    '  exit 1',
    'fi',
    `PID=$(cat ${JSON.stringify(pidFile)})`,
    'kill "$PID"',
    `rm -f ${JSON.stringify(pidFile)}`,
    'echo "Stopped Clawdie"',
    '',
  ].join('\n');
}

describe('FreeBSD wrapper generation', () => {
  it('start wrapper points to dist/index.js', () => {
    const script = generateStartWrapper(
      '/usr/local/bin/node',
      '/home/clawdie/clawdie-ai',
      '/home/clawdie/clawdie-ai/clawdie.pid',
    );
    expect(script).toContain('/home/clawdie/clawdie-ai/dist/index.js');
  });

  it('start wrapper writes pid file', () => {
    const script = generateStartWrapper(
      '/usr/local/bin/node',
      '/home/clawdie/clawdie-ai',
      '/home/clawdie/clawdie-ai/clawdie.pid',
    );
    expect(script).toContain('echo $! > "/home/clawdie/clawdie-ai/clawdie.pid"');
  });

  it('stop wrapper removes pid file', () => {
    const script = generateStopWrapper('/home/clawdie/clawdie-ai/clawdie.pid');
    expect(script).toContain('rm -f "/home/clawdie/clawdie-ai/clawdie.pid"');
  });
});
