import os from 'os';
import path from 'path';

import { runCommand } from './command.js';

const DEFAULT_SSH_OPTIONS = [
  '-o', 'StrictHostKeyChecking=no',
  '-o', 'UserKnownHostsFile=/dev/null',
  '-o', 'BatchMode=yes',
  '-o', 'LogLevel=ERROR'
];

export function expandHomePath(value) {
  if (!value) {
    return value;
  }

  if (value === '~') {
    return os.homedir();
  }

  if (value.startsWith('~/')) {
    return path.join(os.homedir(), value.slice(2));
  }

  return value;
}

export async function runSSH({
  host,
  user,
  command,
  keyPath = process.env.SSH_KEY_PATH ?? '~/.ssh/sc_host_key',
  timeoutSec = 15,
  connectTimeoutSec = 5,
  extraArgs = []
}) {
  const resolvedKeyPath = expandHomePath(keyPath);
  const args = [
    ...DEFAULT_SSH_OPTIONS,
    '-o', `ConnectTimeout=${connectTimeoutSec}`,
    '-i', resolvedKeyPath,
    ...extraArgs,
    `${user}@${host}`,
    command
  ];

  return await runCommand('ssh', args, { timeoutMs: timeoutSec * 1000 });
}
