/** Detect Windows cmd.exe (not PowerShell). */
export function isWindowsCmd(shell: string): boolean {
  const lower = shell.toLowerCase().replace(/\\/g, '/');
  return lower.endsWith('cmd.exe') || lower.includes('/cmd');
}

/** Build a shell-specific change-directory command. */
export function buildCdCommand(cwd: string, shell: string, osPlatform: string): string {
  const trimmed = cwd.trim();
  if (!trimmed || trimmed === '.') return '';

  if (osPlatform === 'windows') {
    if (isWindowsCmd(shell)) {
      return `cd /d ${JSON.stringify(trimmed)}`;
    }
    const escaped = trimmed.replace(/'/g, "''");
    return `Set-Location -LiteralPath '${escaped}'`;
  }
  return `cd ${JSON.stringify(trimmed)}`;
}

function normalizeDir(path: string | undefined): string {
  const trimmed = (path || '').trim();
  if (!trimmed || trimmed === '.') return '';
  return trimmed;
}

/** Resolve the directory a terminal pane should use (never "."). */
export function resolvePaneCwd(paneCwd: string | undefined, workspaceRoot: string): string {
  return normalizeDir(paneCwd) || normalizeDir(workspaceRoot);
}
