import type { BashOperations } from "@earendil-works/pi-coding-agent";
import type { RemoteTransport } from "./ssh2-transport.ts";

export interface RemoteBashConnection {
  remoteCwd: string;
}

/**
 * Adapt Pi's Bash output machinery to the active remote workspace.
 *
 * The cwd supplied by Pi's Bash factory is deliberately ignored: it belongs
 * to the factory's filesystem namespace and must never leak into SSH command
 * execution. The connection's mutable remoteCwd is the sole shell base.
 */
export function createRemoteBashOps(
  connection: RemoteBashConnection,
  transport: RemoteTransport,
): BashOperations {
  return {
    exec: (command, _factoryCwd, { onData, signal, timeout }) => {
      if (!connection.remoteCwd.startsWith("/")) {
        throw new Error(`ssh_bash requires an absolute remote cwd, received '${connection.remoteCwd}'`);
      }
      return transport.exec(command, connection.remoteCwd, { onData, signal, timeout });
    },
  };
}
