#!/usr/bin/env bash
set -euo pipefail

CHATGPT_BIN="${CHATGPT_BIN:-/usr/bin/chatgpt}"
CHATGPT_PROCESS_NAME="${CHATGPT_PROCESS_NAME:-ChatGPT}"
PROC_ROOT="${PROC_ROOT:-/proc}"
PROXY_CLIENT_SHELL="${PROXY_CLIENT_SHELL:-${XDG_CONFIG_HOME:-$HOME/.config}/proxy-client/shell.bash}"

fail_with_notification() {
  local message="$1"
  printf 'Ошибка: %s\n' "$message" >&2
  if command -v notify-send >/dev/null 2>&1; then
    notify-send \
      --app-name='ChatGPT Proxy' \
      --icon=chatgpt \
      'ChatGPT Proxy' \
      "$message" \
      >/dev/null 2>&1 || true
  fi
  exit 1
}

chromium_bypass_list() {
  local source_list="$1" item result=''
  local -a items=()
  IFS=',' read -r -a items <<< "$source_list"

  for item in "${items[@]}"; do
    item="${item#"${item%%[![:space:]]*}"}"
    item="${item%"${item##*[![:space:]]}"}"
    [ -n "$item" ] || continue
    case "$item" in
      .*) item="*$item" ;;
    esac
    if [ -n "$result" ]; then
      result+=';'
    fi
    result+="$item"
  done

  printf '%s\n' "$result"
}

detect_existing_chatgpt() {
  local pgrep_output pgrep_status pid cmdline_text
  local is_main has_proxy_server has_proxy_bypass

  if pgrep_output="$(pgrep -x "$CHATGPT_PROCESS_NAME" 2>/dev/null)"; then
    pgrep_status=0
  else
    pgrep_status=$?
  fi

  case "$pgrep_status" in
    0) ;;
    1)
      printf '%s\n' none
      return 0
      ;;
    *) return 1 ;;
  esac

  while IFS= read -r pid; do
    [ -n "$pid" ] || continue
    [ -r "$PROC_ROOT/$pid/cmdline" ] || continue
    is_main=1
    has_proxy_server=0
    has_proxy_bypass=0

    cmdline_text="$(tr '\0' ' ' < "$PROC_ROOT/$pid/cmdline")"
    case " $cmdline_text " in
      *" --type="*) is_main=0 ;;
    esac
    case " $cmdline_text " in
      *" --proxy-server=$HTTP_PROXY "*) has_proxy_server=1 ;;
    esac
    case " $cmdline_text " in
      *" --proxy-bypass-list=$proxy_bypass_list "*) has_proxy_bypass=1 ;;
    esac

    [ "$is_main" -eq 1 ] || continue
    if [ "$has_proxy_server" -eq 1 ] && [ "$has_proxy_bypass" -eq 1 ]; then
      printf '%s\n' proxied
    else
      printf '%s\n' direct
    fi
    return 0
  done <<< "$pgrep_output"

  printf '%s\n' none
}

if [ ! -x "$CHATGPT_BIN" ]; then
  fail_with_notification "ChatGPT не найден: $CHATGPT_BIN"
fi

if [ ! -r "$PROXY_CLIENT_SHELL" ]; then
  fail_with_notification "Модуль proxy-client не найден: $PROXY_CLIENT_SHELL"
fi

if [ -z "${PROXY_CLIENT_BIN:-}" ] && [ -x "$HOME/.local/bin/proxy-client" ]; then
  PROXY_CLIENT_BIN="$HOME/.local/bin/proxy-client"
  export PROXY_CLIENT_BIN
fi

# shellcheck source=/dev/null
source "$PROXY_CLIENT_SHELL"

if ! proxy_on >/dev/null; then
  fail_with_notification 'Прокси недоступен. Проверьте его командой: proxy-client status'
fi

if [ -z "${HTTP_PROXY:-}" ] || [ -z "${NO_PROXY:-}" ]; then
  fail_with_notification 'proxy-client вернул неполные настройки прокси.'
fi

proxy_bypass_list="$(chromium_bypass_list "$NO_PROXY")"

if ! command -v pgrep >/dev/null 2>&1; then
  fail_with_notification 'Не удалось проверить запущенные процессы: команда pgrep не найдена.'
fi

if ! existing_chatgpt="$(detect_existing_chatgpt)"; then
  fail_with_notification 'Не удалось проверить, запущен ли ChatGPT.'
fi

if [ "$existing_chatgpt" = direct ]; then
  fail_with_notification 'ChatGPT уже работает без прокси. В системном лотке выберите «Quit ChatGPT», затем снова откройте «ChatGPT Proxy». Кнопка «Перезапустить» сохраняет прямой режим.'
fi

exec "$CHATGPT_BIN" \
  "--proxy-server=$HTTP_PROXY" \
  "--proxy-bypass-list=$proxy_bypass_list" \
  "$@"
