import { describe, expect, it } from 'bun:test';
import { looksLikeOpenCodeServe } from './serve-sweep';

// The guard on the pidfile sweep, which is the portable replacement for a `/proc` scan that was a no-op
// on macOS — so orphaned serves accumulated there, one per unclean exit, each holding a port.
//
// The strings below are REAL `ps -p <pid> -o command=` output, captured from the live serve on both
// machines rather than invented: macOS 26 and alpha (Linux). Both print the absolute binary path with no
// leading whitespace, which is the thing worth pinning — a format change is what would silently turn the
// sweep back into a no-op.

const MACOS = '/Users/pastilhas/.opencode/bin/opencode serve --port 55565 --hostname 127.0.0.1';
const LINUX = '/home/pastilhas/.opencode/bin/opencode serve --port 33637 --hostname 127.0.0.1';

describe('looksLikeOpenCodeServe', () => {
  it('recognises the real serve command line on both platforms', () => {
    expect(looksLikeOpenCodeServe(MACOS)).toBe(true);
    expect(looksLikeOpenCodeServe(LINUX)).toBe(true);
    expect(looksLikeOpenCodeServe(`${LINUX}\n`)).toBe(true); // ps leaves the trailing newline on
  });

  it('refuses a pid the OS handed to something else entirely', () => {
    // The whole reason the check exists: the recorded process died and its number was reused, so
    // SIGTERM would hit a bystander.
    expect(looksLikeOpenCodeServe('/Applications/Xcode.app/Contents/MacOS/Xcode')).toBe(false);
    expect(looksLikeOpenCodeServe('')).toBe(false);
    expect(looksLikeOpenCodeServe('   ')).toBe(false);
  });

  it('never matches an `opencode run`, whatever the prompt says', () => {
    // A turn is not a serve, and this is the sharp edge: matching the word `serve` anywhere in the line
    // would sweep a running turn whose PROMPT merely mentioned it. Killing a live turn to tidy up a
    // stale server is the worst outcome available here.
    expect(looksLikeOpenCodeServe('/home/p/.opencode/bin/opencode run --format json "how do I serve this"')).toBe(
      false,
    );
    expect(looksLikeOpenCodeServe('/home/p/.opencode/bin/opencode run --format json serve')).toBe(false);
  });

  it('is not fooled by a path that merely contains the word', () => {
    expect(looksLikeOpenCodeServe('/opt/opencode/server/bin/helper --port 1')).toBe(false);
    expect(looksLikeOpenCodeServe('/usr/bin/serve --port 1')).toBe(false); // no `opencode` in the command
  });
});
