import { describe, it, expect } from 'vitest';
import { shellExecTool } from './shell.js';
import { tmpdir } from 'os';
import { mkdtempSync, writeFileSync, rmSync } from 'fs';
import { join } from 'path';

describe('shell.exec tool', () => {
  it('has correct metadata', () => {
    expect(shellExecTool.name).toBe('shell.exec');
    expect(shellExecTool.inputSchema.required).toContain('command');
  });

  it('runs a simple command', async () => {
    const result = await shellExecTool.execute({ command: 'echo hello' });
    expect(result.success).toBe(true);
    expect(result.output.trim()).toBe('hello');
  });

  it('captures stderr on failure', async () => {
    const result = await shellExecTool.execute({ command: 'ls /nonexistent_dir_xyz' });
    expect(result.success).toBe(false);
    expect(result.error).toBeTruthy();
  });

  it('respects cwd parameter', async () => {
    const dir = mkdtempSync(join(tmpdir(), 'flynn-test-'));
    writeFileSync(join(dir, 'test.txt'), 'content');
    try {
      const result = await shellExecTool.execute({ command: 'ls test.txt', cwd: dir });
      expect(result.success).toBe(true);
      expect(result.output.trim()).toBe('test.txt');
    } finally {
      rmSync(dir, { recursive: true });
    }
  });

  it('respects timeout parameter', async () => {
    const result = await shellExecTool.execute({ command: 'sleep 10', timeout: 200 });
    expect(result.success).toBe(false);
    expect(result.error).toContain('timed out');
  });
});
