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

log() { echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] $*"; }
fail() { echo "ERROR: $*" >&2; exit 1; }

# Required env vars
REQUIRED_VARS=(DB_HOST DB_PORT DB_NAME DB_USER DB_PASS)

MISSING=()
for v in "${REQUIRED_VARS[@]}"; do
  if [[ -z "${!v-}" ]]; then MISSING+=("$v"); fi
done

# Defaults
export PROJECT_DIR="${PROJECT_DIR:-/app}"
export FLASK_APP="${FLASK_APP:-${PROJECT_DIR}/scripts/run.py}"
export COMPONENT_NAME="${COMPONENT_NAME:-eveai_app}"
export PYTHONPATH="${PYTHONPATH:-${PROJECT_DIR}:${PYTHONPATH-}}"

if ((${#MISSING[@]})); then
  fail "Missing required env vars: ${MISSING[*]}"
fi

# Tools check
need() { command -v "$1" >/dev/null 2>&1 || fail "Required tool not found in PATH: $1"; }
need psql
need pg_isready
need flask

log "Environment OK"
log "DB_HOST=$DB_HOST DB_PORT=$DB_PORT DB_NAME=$DB_NAME"
log "PROJECT_DIR=$PROJECT_DIR"
log "FLASK_APP=$FLASK_APP COMPONENT_NAME=$COMPONENT_NAME"

# Versions (do not leak secrets)
psql --version || true
flask --version || true

log "00-env-check completed successfully."