import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir, platform } from 'node:os';

export type ShellType = 'zsh' | 'bash' | 'fish' | 'powershell' | 'unknown';

export function detectShell(): ShellType {
  const shell = process.env['SHELL'] ?? '';
  if (shell.includes('zsh')) return 'zsh';
  if (shell.includes('bash')) return 'bash';
  if (shell.includes('fish')) return 'fish';
  if (platform() === 'win32') return 'powershell';
  return 'unknown';
}

export function getShellProfilePath(): string | null {
  const home = homedir();

  if (platform() === 'win32') {
    return join(home, 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1');
  }

  const shell = detectShell();
  switch (shell) {
    case 'zsh': {
      const zdotdir = process.env['ZDOTDIR'] ?? home;
      return join(zdotdir, '.zshrc');
    }
    case 'bash': {
      const bashrc = join(home, '.bashrc');
      if (existsSync(bashrc)) return bashrc;
      return join(home, '.profile');
    }
    case 'fish':
      return join(home, '.config', 'fish', 'config.fish');
    default:
      return join(home, '.profile');
  }
}
