#!/usr/bin/env bash

set -euo pipefail

cd "$(dirname "${BASH_SOURCE[0]}")"

HOST="${PHUTBALL_HOST:-127.0.0.1}"
PORT="${PHUTBALL_PORT:-8080}"
MAX_PORT="${PHUTBALL_MAX_PORT:-8099}"
PYTHON_BIN="${PHUTBALL_PYTHON:-}"
INSTALL_AI="${PHUTBALL_INSTALL_AI:-auto}"

choose_python() {
  if [ -n "${PYTHON_BIN}" ]; then
    printf '%s\n' "${PYTHON_BIN}"
    return
  fi

  if [ ! -x ".venv/bin/python" ]; then
    echo "Creating local Python environment in .venv..." >&2
    python3 -m venv .venv
  fi
  printf '%s\n' ".venv/bin/python"
}

port_is_free() {
  local port="$1"
  "${PYTHON}" - "$HOST" "$port" <<'PY'
import socket
import sys

host = sys.argv[1]
port = int(sys.argv[2])

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        sock.bind((host, port))
    except OSError:
        raise SystemExit(1)
PY
}

find_port() {
  local port="$PORT"
  while [ "$port" -le "$MAX_PORT" ]; do
    if port_is_free "$port"; then
      printf '%s\n' "$port"
      return
    fi
    port=$((port + 1))
  done
  echo "No free port found from ${PORT} through ${MAX_PORT}." >&2
  exit 1
}

has_web_dependencies() {
  "${PYTHON}" - <<'PY'
import flask
import flask_cors
import numpy
PY
}

has_torch() {
  "${PYTHON}" - <<'PY'
import torch
PY
}

has_model_files() {
  find models -maxdepth 1 -type f -name '*.pt' 2>/dev/null | grep -q .
}

should_install_ai() {
  case "${INSTALL_AI}" in
    1|true|yes)
      return 0
      ;;
    0|false|no)
      return 1
      ;;
    auto)
      has_model_files
      return
      ;;
    *)
      echo "Invalid PHUTBALL_INSTALL_AI='${INSTALL_AI}'. Use auto, 1, or 0." >&2
      exit 1
      ;;
  esac
}

wait_for_server() {
  local url="$1"
  for _ in $(seq 1 80); do
    if "${PYTHON}" - "$url" <<'PY'
import sys
import urllib.request

try:
    urllib.request.urlopen(sys.argv[1], timeout=0.25).close()
except Exception:
    raise SystemExit(1)
PY
    then
      return 0
    fi
    sleep 0.25
  done
  return 1
}

browser_host() {
  case "${HOST}" in
    0.0.0.0|::)
      printf '%s\n' "127.0.0.1"
      ;;
    *)
      printf '%s\n' "${HOST}"
      ;;
  esac
}

PYTHON="$(choose_python)"

"${PYTHON}" -m ensurepip --upgrade >/dev/null 2>&1 || true

if ! has_web_dependencies; then
  echo "Installing Phutball Simplified web dependencies..."
  "${PYTHON}" -m pip install -r requirements.txt
fi

AI_REQUESTED=0
if should_install_ai; then
  AI_REQUESTED=1
  if ! has_torch; then
    echo "Installing PyTorch dependencies for AI play..."
    "${PYTHON}" -m pip install -r requirements-ai.txt
  fi
fi

if [ "${AI_REQUESTED}" -eq 1 ] && ! has_torch; then
  echo "PyTorch is not installed in ${PYTHON}; local play works, AI analysis will be disabled."
  echo "To install AI dependencies, rerun with: PHUTBALL_INSTALL_AI=1 ./play-phutball-simplified.sh"
  echo "To use an existing torch environment, rerun with: PHUTBALL_PYTHON=/path/to/python ./play-phutball-simplified.sh"
fi

PORT="$(find_port)"
BROWSER_HOST="$(browser_host)"
URL="http://${BROWSER_HOST}:${PORT}"
HEALTH_URL="http://${HOST}:${PORT}/health"

echo "Starting Phutball Simplified with ${PYTHON}"
echo "URL: ${URL}"

"${PYTHON}" server.py --host "${HOST}" --port "${PORT}" &
SERVER_PID=$!

cleanup() {
  kill "${SERVER_PID}" 2>/dev/null || true
}
trap cleanup EXIT INT TERM HUP

if wait_for_server "${HEALTH_URL}"; then
  if command -v xdg-open >/dev/null 2>&1; then
    xdg-open "${URL}" >/dev/null 2>&1 || true
  fi
  echo "Server is ready. Press Ctrl+C to stop."
  wait "${SERVER_PID}"
else
  echo "Phutball Simplified did not become ready at ${URL}." >&2
  exit 1
fi
