#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${OMEMAI_GATEWAY_ENV:-$ROOT/.env}"
SESSION="${OMEMAI_GATEWAY_TMUX_SESSION:-omemai-gateway}"
HOST="127.0.0.1"
PORT="8777"
if [[ -f "$ENV_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$ENV_FILE" || true
  HOST="${OMEMAI_GATEWAY_HOST:-127.0.0.1}"
  PORT="${OMEMAI_GATEWAY_PORT:-8777}"
fi
echo "workdir=$ROOT"
if command -v tmux >/dev/null 2>&1 && tmux has-session -t "$SESSION" 2>/dev/null; then
  echo "tmux_session=$SESSION running"
else
  echo "tmux_session=$SESSION not_running"
fi
python3 - <<PY
import socket
host="$HOST"; port=int("$PORT")
s=socket.socket(); s.settimeout(2)
try:
    s.connect((host, port)); print(f"tcp={host}:{port} listening")
except Exception as exc:
    print(f"tcp={host}:{port} not_listening error={exc}")
finally:
    s.close()
PY
curl -s --connect-timeout 2 --max-time 5 "http://$HOST:$PORT" \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"gateway.status","params":{}}' || true
echo
