#!/usr/bin/env bash
# Validate that a locally built wheel can be installed as a uv tool and serves authenticated /health.
set -euo pipefail

if ! command -v uv >/dev/null 2>&1; then
  echo "uv not found in PATH" >&2
  exit 1
fi

if ! command -v curl >/dev/null 2>&1; then
  echo "curl not found in PATH" >&2
  exit 1
fi

python_bin="${PYTHON_BIN:-}"
if [[ -z "${python_bin}" ]]; then
  if command -v python3 >/dev/null 2>&1; then
    python_bin="python3"
  elif command -v python >/dev/null 2>&1; then
    python_bin="python"
  else
    echo "python3 or python not found in PATH" >&2
    exit 1
  fi
fi

shopt -s nullglob
wheel_paths=(dist/codex_a2a-*.whl)
shopt -u nullglob

wheel_path="${WHEEL_PATH:-}"

if [[ -z "${wheel_path}" ]]; then
  if [[ "${#wheel_paths[@]}" -eq 0 ]]; then
    echo "No built wheel found in dist/" >&2
    exit 1
  fi
  if [[ "${#wheel_paths[@]}" -gt 1 ]]; then
    echo "Multiple built wheels found in dist/; set WHEEL_PATH explicitly." >&2
    exit 1
  fi
  wheel_path="${wheel_paths[0]}"
fi

if [[ ! -f "${wheel_path}" ]]; then
  echo "Wheel path does not exist: ${wheel_path}" >&2
  exit 1
fi

tmpdir="$(mktemp -d)"
tool_dir="${tmpdir}/tools"
tool_bin_dir="${tmpdir}/bin"
fake_codex_bin="${tmpdir}/codex"
server_log="${tmpdir}/server.log"
database_path="${tmpdir}/codex-a2a-smoke.db"

cleanup() {
  local exit_code="$1"
  if [[ -n "${server_pid:-}" ]] && kill -0 "${server_pid}" >/dev/null 2>&1; then
    kill "${server_pid}" >/dev/null 2>&1 || true
    wait "${server_pid}" >/dev/null 2>&1 || true
  fi
  rm -rf "${tmpdir}"
  exit "${exit_code}"
}

trap 'cleanup $?' EXIT

mkdir -p "${tool_dir}" "${tool_bin_dir}"

export PATH="${tool_bin_dir}:${PATH}"

UV_TOOL_DIR="${tool_dir}" \
UV_TOOL_BIN_DIR="${tool_bin_dir}" \
UV_LINK_MODE="copy" \
uv tool install "${wheel_path}" --python "${python_bin}"

mapfile -t installed_python_paths < <(
  find "${tool_dir}" \( -type f -o -type l \) -path '*/bin/python' | sort
)
if [[ "${#installed_python_paths[@]}" -ne 1 ]]; then
  echo "Expected exactly one installed tool python, found ${#installed_python_paths[@]}" >&2
  printf ' - %s\n' "${installed_python_paths[@]}" >&2 || true
  exit 1
fi
installed_python="${installed_python_paths[0]}"

"${installed_python}" -c "import codex_a2a; print(codex_a2a.__version__)" >/dev/null

cat >"${fake_codex_bin}" <<'PY'
#!/usr/bin/env python3
import json
import sys


for raw_line in sys.stdin:
    line = raw_line.strip()
    if not line:
        continue
    message = json.loads(line)
    request_id = message.get("id")
    method = message.get("method")
    if request_id is None:
        continue
    response = {"jsonrpc": "2.0", "id": request_id, "result": {}}
    if method == "initialize":
        response["result"] = {"capabilities": {}}
    sys.stdout.write(json.dumps(response) + "\n")
    sys.stdout.flush()
PY
chmod +x "${fake_codex_bin}"

port="$(
  "${python_bin}" - <<'PY'
import socket

with socket.socket() as sock:
    sock.bind(("127.0.0.1", 0))
    print(sock.getsockname()[1])
PY
)"

bearer_token="smoke-test-token"

A2A_STATIC_AUTH_CREDENTIALS='[{"id":"smoke-bearer","scheme":"bearer","token":"'"${bearer_token}"'","principal":"automation"}]' \
A2A_DATABASE_URL="sqlite+aiosqlite:///${database_path}" \
A2A_PORT="${port}" \
A2A_HOST="127.0.0.1" \
CODEX_CLI_BIN="${fake_codex_bin}" \
"${tool_bin_dir}/codex-a2a" >"${server_log}" 2>&1 &
server_pid="$!"

health_url="http://127.0.0.1:${port}/health"
for _ in $(seq 1 50); do
  if curl -fsS -H "Authorization: Bearer ${bearer_token}" "${health_url}" >/dev/null 2>&1; then
    exit 0
  fi
  sleep 0.2
done

echo "CLI smoke test failed; server did not become healthy at ${health_url}" >&2
cat "${server_log}" >&2
exit 1
