/**
 * Utility for generating user-friendly error messages with actionable steps
 * Helps users understand what went wrong and how to fix it
 */

export interface ErrorMessage {
  title: string;
  description: string;
  possibleCauses?: string[];
  suggestedActions?: string[];
  technicalDetails?: string;
}

/**
 * Parse error and generate user-friendly message with suggested actions
 */
export function getErrorMessage(error: Error | string, context?: string): ErrorMessage {
  const errorText = typeof error === 'string' ? error : error.message;
  const errorLower = errorText.toLowerCase();

  // Network errors
  if (errorLower.includes('enotfound') || errorLower.includes('getaddrinfo') || errorLower.includes('network')) {
    return {
      title: 'Network Connection Error',
      description: 'Unable to connect to the internet or required services.',
      possibleCauses: [
        'No internet connection',
        'VPN or proxy blocking access',
        'DNS resolution failure',
        'Firewall blocking connection'
      ],
      suggestedActions: [
        'Check your internet connection',
        'Disable VPN/proxy temporarily and try again',
        'Check your firewall settings',
        'Try again in a few moments'
      ],
      technicalDetails: errorText
    };
  }

  // Git/SSH errors - check before generic permission errors
  if (context?.includes('git') || context?.includes('ssh') || errorLower.includes('git') || errorLower.includes('ssh')) {
    if (errorLower.includes('permission denied') && errorLower.includes('publickey')) {
      return {
        title: 'SSH Authentication Failed',
        description: 'Git couldn\'t authenticate using your SSH key.',
        possibleCauses: [
          'SSH key not added to your account',
          'SSH key not loaded in ssh-agent',
          'Wrong SSH key being used',
          'SSH key passphrase required'
        ],
        suggestedActions: [
          'Verify SSH key is added to GitHub/Gerrit',
          'Test connection: ssh -T git@github.com',
          'Add key to ssh-agent: ssh-add ~/.ssh/id_ed25519',
          'Check SSH config file: ~/.ssh/config'
        ],
        technicalDetails: errorText
      };
    }

    if (errorLower.includes('repository not found') || errorLower.includes('could not read from remote')) {
      return {
        title: 'Repository Access Error',
        description: 'Unable to access the Git repository.',
        possibleCauses: [
          'Repository doesn\'t exist',
          'No access permissions',
          'Incorrect repository URL',
          'Network connectivity issues'
        ],
        suggestedActions: [
          'Verify the repository exists',
          'Check you have access permissions',
          'Ensure SSH keys are configured correctly',
          'Try cloning with HTTPS instead of SSH'
        ],
        technicalDetails: errorText
      };
    }
  }

  // Permission errors
  if (errorLower.includes('eacces') || errorLower.includes('permission denied') || errorLower.includes('eperm')) {
    return {
      title: 'Permission Denied',
      description: 'The application doesn\'t have permission to perform this operation.',
      possibleCauses: [
        'Insufficient file system permissions',
        'Protected system directory',
        'File in use by another process',
        'macOS security restrictions'
      ],
      suggestedActions: [
        'Try running the operation again',
        'Check file/directory permissions',
        'Close other applications that might be using the file',
        'Grant necessary permissions in System Preferences > Security & Privacy'
      ],
      technicalDetails: errorText
    };
  }

  // Homebrew specific errors
  if (context?.includes('homebrew') || errorLower.includes('brew')) {
    if (errorLower.includes('command not found')) {
      return {
        title: 'Homebrew Not Found',
        description: 'Homebrew is not installed or not in your PATH.',
        possibleCauses: [
          'Homebrew is not installed',
          'Shell PATH not configured correctly',
          'Terminal needs to be restarted'
        ],
        suggestedActions: [
          'Install Homebrew from https://brew.sh',
          'Restart your terminal or computer',
          'Check if Homebrew is installed: which brew',
          'Verify PATH includes /opt/homebrew/bin'
        ],
        technicalDetails: errorText
      };
    }

    if (errorLower.includes('lock')) {
      return {
        title: 'Homebrew Lock File',
        description: 'Another Homebrew operation is in progress or was interrupted.',
        possibleCauses: [
          'Another Homebrew process is running',
          'Previous installation was interrupted',
          'Stale lock file exists'
        ],
        suggestedActions: [
          'Wait for other Homebrew operations to complete',
          'Run: brew cleanup',
          'If stuck, run: rm -rf "$(brew --prefix)/var/homebrew/locks"',
          'Try the operation again'
        ],
        technicalDetails: errorText
      };
    }
  }

  // Docker specific errors
  if (context?.includes('docker') || errorLower.includes('docker')) {
    if (errorLower.includes('cannot connect') || errorLower.includes('daemon')) {
      return {
        title: 'Docker Daemon Not Running',
        description: 'Docker Desktop is not running or not accessible.',
        possibleCauses: [
          'Docker Desktop is not installed',
          'Docker Desktop is not running',
          'Docker daemon failed to start',
          'Permission issues with Docker socket'
        ],
        suggestedActions: [
          'Open Docker Desktop application',
          'Wait for Docker to fully start (check menu bar icon)',
          'Restart Docker Desktop',
          'Reinstall Docker if issues persist'
        ],
        technicalDetails: errorText
      };
    }

    if (errorLower.includes('memory') || errorLower.includes('resources')) {
      return {
        title: 'Docker Resource Limit',
        description: 'Docker has insufficient resources allocated.',
        possibleCauses: [
          'Docker memory limit too low',
          'System resources exhausted',
          'Too many containers running'
        ],
        suggestedActions: [
          'Open Docker Desktop Preferences',
          'Increase memory allocation to at least 8GB',
          'Stop unused containers: docker stop $(docker ps -q)',
          'Restart Docker Desktop'
        ],
        technicalDetails: errorText
      };
    }
  }

  // File system errors
  if (errorLower.includes('enoent') || errorLower.includes('no such file')) {
    return {
      title: 'File or Directory Not Found',
      description: 'Required file or directory doesn\'t exist.',
      possibleCauses: [
        'File was moved or deleted',
        'Incorrect file path',
        'File hasn\'t been created yet',
        'Previous step not completed'
      ],
      suggestedActions: [
        'Verify the file path is correct',
        'Complete previous setup steps',
        'Create the required directory manually',
        'Refresh the status to update'
      ],
      technicalDetails: errorText
    };
  }

  // Timeout errors
  if (errorLower.includes('timeout') || errorLower.includes('etimedout')) {
    return {
      title: 'Operation Timed Out',
      description: 'The operation took too long to complete.',
      possibleCauses: [
        'Slow internet connection',
        'Server not responding',
        'Large download in progress',
        'System under heavy load'
      ],
      suggestedActions: [
        'Check your internet connection speed',
        'Try again - downloads may take several minutes',
        'Close other applications to free resources',
        'Try during off-peak hours'
      ],
      technicalDetails: errorText
    };
  }

  // Generic error
  return {
    title: 'Operation Failed',
    description: context ? `Failed to ${context}` : 'An unexpected error occurred.',
    possibleCauses: [
      'System configuration issue',
      'Temporary service disruption',
      'Incomplete previous setup'
    ],
    suggestedActions: [
      'Try the operation again',
      'Restart the application',
      'Check system logs for details',
      'Contact support if the issue persists'
    ],
    technicalDetails: errorText
  };
}

/**
 * Format error message for display in UI
 */
export function formatErrorMessage(errorMsg: ErrorMessage): string {
  let message = `${errorMsg.title}\n\n${errorMsg.description}`;

  if (errorMsg.possibleCauses && errorMsg.possibleCauses.length > 0) {
    message += '\n\nPossible causes:\n';
    message += errorMsg.possibleCauses.map(cause => `• ${cause}`).join('\n');
  }

  if (errorMsg.suggestedActions && errorMsg.suggestedActions.length > 0) {
    message += '\n\nSuggested actions:\n';
    message += errorMsg.suggestedActions.map((action, i) => `${i + 1}. ${action}`).join('\n');
  }

  return message;
}

/**
 * Format error message for logging
 */
export function formatErrorForLogging(error: Error | string, context?: string): string {
  const errorMsg = getErrorMessage(error, context);
  return `${errorMsg.title}: ${errorMsg.description}\nTechnical: ${errorMsg.technicalDetails || error}`;
}
