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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COGNITO_ENV_FILE="$SCRIPT_DIR/docker/floci/generated/cognito.local.env"

MIN_JAVA_VERSION=25

is_valid_jdk() {
  [[ -n "${1:-}" && -x "$1/bin/java" ]]
}

java_major_version() {
  "$1/bin/java" -version 2>&1 | awk -F '"' '/version/ { split($2, v, "."); print v[1]; exit }'
}

collect_jdk_candidates() {
  local -a candidates=()

  if [[ -n "${JAVA_HOME:-}" ]]; then
    candidates+=("$JAVA_HOME")
  fi

  if compgen -G "/opt/jdk-*" > /dev/null; then
    while IFS= read -r jdk_dir; do
      candidates+=("$jdk_dir")
    done < <(ls -d /opt/jdk-* 2>/dev/null | sort -rV)
  fi

  candidates+=(
    /usr/lib/jvm/java-25-temurin-jdk
    /usr/lib/jvm/java-21-temurin-jdk
    /usr/lib/jvm/java-21-openjdk-amd64
  )

  printf '%s\n' "${candidates[@]}"
}

resolve_java_home() {
  local candidate major_version
  local -A seen=()

  if [[ -n "${JAVA_HOME:-}" && ! -x "${JAVA_HOME}/bin/java" ]]; then
    echo "JAVA_HOME actual ($JAVA_HOME) no es valido. Buscando otro JDK..." >&2
  fi

  while IFS= read -r candidate; do
    [[ -n "$candidate" && -z "${seen[$candidate]+x}" ]] || continue
    seen[$candidate]=1

    if ! is_valid_jdk "$candidate"; then
      continue
    fi

    major_version="$(java_major_version "$candidate")"
    if (( major_version >= MIN_JAVA_VERSION )); then
      echo "$candidate"
      return 0
    fi
  done < <(collect_jdk_candidates)

  while IFS= read -r candidate; do
    [[ -n "$candidate" && -z "${seen[$candidate]+x}" ]] || continue
    seen[$candidate]=1

    if is_valid_jdk "$candidate"; then
      major_version="$(java_major_version "$candidate")"
      echo "Se encontro Java $major_version en $candidate, pero este proyecto requiere Java $MIN_JAVA_VERSION o superior." >&2
      return 1
    fi
  done < <(collect_jdk_candidates)

  echo "No se encontro un JDK valido. Instala Temurin $MIN_JAVA_VERSION+ o define JAVA_HOME." >&2
  return 1
}

wait_for_cognito_env() {
  local elapsed=0
  local timeout=120

  while [[ ! -f "$COGNITO_ENV_FILE" && $elapsed -lt $timeout ]]; do
    sleep 2
    elapsed=$((elapsed + 2))
    if (( elapsed % 10 == 0 )); then
      echo "Esperando bootstrap de Cognito en Floci..." >&2
    fi
  done

  [[ -f "$COGNITO_ENV_FILE" ]]
}

load_cognito_local_env() {
  if [[ -n "${AWS_ENDPOINT_URL:-}" ]]; then
    echo "AWS_ENDPOINT_URL ya definido; omitiendo carga de cognito.local.env" >&2
    return 0
  fi

  if [[ ! -f "$COGNITO_ENV_FILE" ]]; then
    echo "No se encontro $COGNITO_ENV_FILE. Exporta las variables Cognito manualmente." >&2
    return 1
  fi

  set -a
  # shellcheck disable=SC1090
  source "$COGNITO_ENV_FILE"
  set +a
  echo "Variables Cognito cargadas desde docker/floci/generated/cognito.local.env" >&2
}

JAVA_HOME="$(resolve_java_home)"
export JAVA_HOME
export PATH="$JAVA_HOME/bin:$PATH"

echo "Usando JAVA_HOME=$JAVA_HOME ($(java -version 2>&1 | head -1))" >&2

PROFILE="${SPRING_PROFILES_ACTIVE:-dev}"

echo "Perfil activo: $PROFILE" >&2
if [[ "$PROFILE" == *"postgres"* ]]; then
  echo "Base de datos: PostgreSQL (${SPRING_DATASOURCE_URL:-jdbc:postgresql://localhost:5432/base_admin_web})" >&2
else
  echo "Base de datos: H2 en archivo local (./data/h2/). Para PostgreSQL usa: SPRING_PROFILES_ACTIVE=postgres ./run-local.sh" >&2
fi

FLOCI_STARTED=false

if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
  COMPOSE_FILE="$SCRIPT_DIR/docker-compose.local.yml"
  mkdir -p "$SCRIPT_DIR/docker/floci/generated"
  chmod 777 "$SCRIPT_DIR/docker/floci/generated" 2>/dev/null || true

  if [[ "$PROFILE" == *"postgres"* ]]; then
    echo "Levantando PostgreSQL y Floci (Cognito local)..." >&2
    docker compose -f "$COMPOSE_FILE" up -d postgres floci
  else
    echo "Levantando Floci (Cognito local) en http://localhost:4566 ..." >&2
    docker compose -f "$COMPOSE_FILE" up -d floci
  fi
  FLOCI_STARTED=true
elif [[ "$PROFILE" == *"postgres"* ]]; then
  echo "Docker Compose no esta disponible. Instala Docker o levanta PostgreSQL manualmente." >&2
  exit 1
fi

if [[ "$FLOCI_STARTED" == true ]]; then
  if wait_for_cognito_env; then
    load_cognito_local_env || true
  else
    echo "Advertencia: timeout esperando cognito.local.env. Revisa Floci o exporta las variables manualmente." >&2
  fi
fi

cd "$SCRIPT_DIR"

mvn -pl base-admin-web-jar -am -DskipTests install
mvn -pl base-admin-web-jar spring-boot:run