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

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

if [[ -n "${AI_GATEWAY_PG_CONTAINER:-}" ]]; then
  CONTAINER="$AI_GATEWAY_PG_CONTAINER"
elif docker inspect easyai-pgvector >/dev/null 2>&1; then
  CONTAINER="easyai-pgvector"
elif docker inspect postgres >/dev/null 2>&1; then
  CONTAINER="postgres"
else
  CONTAINER="$(
    docker compose -f "${PROJECT_ROOT}/docker-compose.yml" ps -q postgres 2>/dev/null \
      | head -n 1
  )"
fi

if [[ -z "$CONTAINER" ]] || ! docker inspect "$CONTAINER" >/dev/null 2>&1; then
  echo "[ai-gateway] no PostgreSQL Docker container found; set AI_GATEWAY_PG_CONTAINER or create the database through the configured connection" >&2
  exit 1
fi
PGUSER="${AI_GATEWAY_PG_USER:-easyai}"
DB_NAME="${AI_GATEWAY_DATABASE_NAME:-easyai_ai_gateway}"

wait_for_postgres() {
  local status

  status="$(docker inspect "$CONTAINER" --format '{{.State.Status}}')"
  if [[ "$status" != "running" ]]; then
    echo "[ai-gateway] starting PostgreSQL container: ${CONTAINER}"
    docker start "$CONTAINER" >/dev/null
  fi

  for _ in {1..30}; do
    if docker exec "$CONTAINER" \
      pg_isready -U "$PGUSER" -d postgres >/dev/null 2>&1; then
      return 0
    fi

    status="$(docker inspect "$CONTAINER" --format '{{.State.Status}}')"
    if [[ "$status" != "running" ]]; then
      echo "[ai-gateway] PostgreSQL container stopped before becoming ready: ${CONTAINER} (${status})" >&2
      return 1
    fi
    sleep 1
  done

  echo "[ai-gateway] timed out waiting for PostgreSQL container: ${CONTAINER}" >&2
  return 1
}

wait_for_postgres

version_num="$(
  docker exec "$CONTAINER" \
    psql -U "$PGUSER" -d postgres -tAc "SHOW server_version_num" \
    | tr -d '[:space:]'
)"

if [[ "${version_num:-0}" -lt 180000 ]]; then
  echo "[ai-gateway] warning: PostgreSQL 18 is expected, current server_version_num=${version_num}"
fi

exists="$(
  docker exec "$CONTAINER" \
    psql -U "$PGUSER" -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname='${DB_NAME}'" \
    | tr -d '[:space:]'
)"

if [[ "$exists" == "1" ]]; then
  echo "[ai-gateway] database already exists: ${DB_NAME}"
  exit 0
fi

docker exec "$CONTAINER" \
  psql -U "$PGUSER" -d postgres -c "CREATE DATABASE \"${DB_NAME}\""

echo "[ai-gateway] database created: ${DB_NAME}"
