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

BACKEND_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DEPLOY_DIR="$BACKEND_DIR/deploy"
COMPOSE_FILE="$DEPLOY_DIR/docker-compose.prod.yml"
ENV_FILE="$DEPLOY_DIR/.env"
ENV_EXAMPLE="$DEPLOY_DIR/.env.example"

if [[ ! -f "$ENV_FILE" ]]; then
  if [[ -f "$ENV_EXAMPLE" ]]; then
    cp "$ENV_EXAMPLE" "$ENV_FILE"
    echo "[prod] created $ENV_FILE from .env.example — 請先修改密鑰與管理員密碼"
  else
    echo "[prod] missing $ENV_FILE" >&2
    exit 1
  fi
fi

set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

GO_REPLICAS="${GO_WORKER_REPLICAS:-1}"
NODE_REPLICAS="${NODE_STYLE8D_WORKER_REPLICAS:-1}"
WEB_PORT="${HAIXUN_WEB_PORT:-8080}"

if ! command -v docker >/dev/null 2>&1; then
  echo "[prod] docker is required" >&2
  exit 1
fi

cd "$DEPLOY_DIR"

echo "[prod] building images..."
docker compose -f "$COMPOSE_FILE" build

echo "[prod] starting mongo + redis..."
docker compose -f "$COMPOSE_FILE" up -d mongo redis

echo "[prod] waiting for mongo/redis..."
for _ in $(seq 1 90); do
  mongo_ok=$(docker compose -f "$COMPOSE_FILE" ps --format json mongo 2>/dev/null | grep -o '"Health":"[^"]*"' | head -1 | cut -d'"' -f4 || true)
  redis_ok=$(docker compose -f "$COMPOSE_FILE" ps --format json redis 2>/dev/null | grep -o '"Health":"[^"]*"' | head -1 | cut -d'"' -f4 || true)
  if [[ "$mongo_ok" == "healthy" && "$redis_ok" == "healthy" ]]; then
    break
  fi
  sleep 1
done

if [[ "${HAIXUN_SKIP_INIT:-0}" != "1" ]]; then
  echo "[prod] running bootstrap init..."
  docker compose -f "$COMPOSE_FILE" --profile init run --rm init
else
  echo "[prod] skip init (HAIXUN_SKIP_INIT=1)"
fi

echo "[prod] starting api, web, workers (go=${GO_REPLICAS}, node-style-8d=${NODE_REPLICAS})..."
docker compose -f "$COMPOSE_FILE" up -d \
  --scale "go-worker=${GO_REPLICAS}" \
  --scale "node-worker-style-8d=${NODE_REPLICAS}" \
  api web go-worker node-worker-style-8d

echo "[prod] waiting for API health..."
for _ in $(seq 1 60); do
  if curl -fsS "http://127.0.0.1:${WEB_PORT}/api/v1/health" >/dev/null 2>&1; then
    break
  fi
  sleep 1
done

echo ""
echo "[prod] stack is up"
echo "  Web:        http://127.0.0.1:${WEB_PORT}"
echo "  API:        http://127.0.0.1:${WEB_PORT}/api/v1/health (via nginx)"
echo "  Go worker:  ${GO_REPLICAS} replica(s)"
echo "  Node 8D:    ${NODE_REPLICAS} replica(s)"
echo "  Env:        ${ENV_FILE}"
echo "  Stop:       make -C haixun-backend prod-down"
echo "  Logs:       make -C haixun-backend prod-logs"