{ pkgs, ... }:

pkgs.writeShellScriptBin "tea" ''
  set -euo pipefail

  # Check if tea config directory exists and has authentication
  TEA_CONFIG_DIR="''${XDG_CONFIG_HOME:-$HOME/.config}/tea"
  TEA_CONFIG_FILE="$TEA_CONFIG_DIR/config.yml"

  # Function to setup tea authentication with rbw
  setup_tea_auth() {
    echo "Tea authentication not found. Setting up with rbw..."
    
    # Check if rbw is available
    if ! command -v rbw &> /dev/null; then
      echo "Error: rbw is not available. Please ensure rbw is installed and configured."
      exit 1
    fi

    # Try to get the token from rbw
    echo "Attempting to retrieve Gitea token from rbw..."
    echo "Please enter the rbw entry name for your Gitea token:"
    read -r rbw_entry

    if ! token=$(rbw get "$rbw_entry" 2>/dev/null); then
      echo "Error: Failed to retrieve token from rbw entry '$rbw_entry'"
      echo "Available rbw entries:"
      rbw list 2>/dev/null || echo "Failed to list rbw entries"
      exit 1
    fi

    # Prompt for Gitea URL
    echo "Please enter your Gitea URL (e.g., https://git.example.com):"
    read -r gitea_url

    # Create tea config directory if it doesn't exist
    mkdir -p "$TEA_CONFIG_DIR"

    # Setup tea login
    if ! ${pkgs.tea}/bin/tea login add --name "default" --url "$gitea_url" --token "$token"; then
      echo "Error: Failed to setup tea authentication"
      exit 1
    fi

    echo "Tea authentication setup complete!"
  }

  # Check if tea is already configured
  if [[ ! -f "$TEA_CONFIG_FILE" ]]; then
    setup_tea_auth
  elif ! ${pkgs.tea}/bin/tea whoami &>/dev/null; then
    echo "Tea config exists but authentication failed. Re-running setup..."
    setup_tea_auth
  fi

  # Execute tea with all provided arguments
  exec ${pkgs.tea}/bin/tea "$@"
''