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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ -f "${SCRIPT_DIR}/docker-compose.yml" ]]; then
  ROOT_DIR="${SCRIPT_DIR}"
else
  ROOT_DIR="$(cd "${SCRIPT_DIR}"/../.. && pwd)"
fi
cd "${ROOT_DIR}"

if ! command -v docker >/dev/null 2>&1; then
  echo "Docker no esta instalado o no esta en PATH." >&2
  exit 1
fi

if ! docker compose version >/dev/null 2>&1; then
  echo "Docker Compose Plugin no esta disponible." >&2
  exit 1
fi

if [[ ! -f ".env" ]]; then
  if [[ -f ".env.example" ]]; then
    cp ".env.example" ".env"
    echo "Se creo .env desde .env.example. Ajusta credenciales antes de continuar." >&2
    exit 1
  fi
  if [[ -f "docker/server/.env.example" ]]; then
    cp "docker/server/.env.example" ".env"
    echo "Se creo .env desde docker/server/.env.example. Ajusta credenciales antes de continuar." >&2
    exit 1
  fi
  echo "Falta .env en el directorio raiz." >&2
  exit 1
fi

mkdir -p logs

docker compose build --pull
docker compose up -d

echo "Despliegue iniciado."
echo "App: http://$(hostname -I 2>/dev/null | awk '{print $1}' || echo 'SERVIDOR'):7000"
echo "Health local: curl http://127.0.0.1:7000/health"
