#!/bin/sh

translate() {
  text="$1"
  lang="$2"
  
  case "$lang" in
    persian|fa|per) lang="fa" ;;
    german|de|ger) lang="de" ;;
    french|fr|fre) lang="fr" ;;
    spanish|es|spa) lang="es" ;;
    *) lang="$lang" ;;
  esac

  if command -v jq >/dev/null 2>&1; then
    translated=$(curl -s "https://libretranslate.de/translate" \
      -d "q=$text" -d "source=auto" -d "target=$lang" \
      -H "Content-Type: application/x-www-form-urlencoded" \
      | jq -r '.translatedText')
  else
    translated=$(curl -s "https://libretranslate.de/translate" \
      -d "q=$text" -d "source=auto" -d "target=$lang" \
      -H "Content-Type: application/x-www-form-urlencoded" \
      | sed -n 's/.*"translatedText":"\([^"]*\)".*/\1/p')
  fi

  printf "\033[1;34mOriginal:\033[0m %s\n" "$text"
  printf "\033[1;33mTranslation (%s):\033[0m %s\n" "$lang" "$translated"
}

if ! command -v curl >/dev/null 2>&1; then
  echo "Error: curl is required" >&2
  exit 1
fi

case "$1" in
  -w|--word|-s|--sentence)
    [ -z "$3" ] && { echo "Usage: $0 [-w|-s] TEXT LANGUAGE" >&2; exit 1; }
    translate "$2" "$3"
    ;;
  *)
    echo "Usage: $0 [-w|-s] TEXT LANGUAGE" >&2
    echo "  -w, --word      Translate a word" >&2
    echo "  -s, --sentence  Translate a sentence" >&2
    echo "Example: $0 -w hello persian" >&2
    exit 1
    ;;
esac