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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
BARON_DIR="${BARON_SSO_WORKTREE:-/home/ubuntu/workspace/baron-sso-tdc114plus-api}"

failures=0
warnings=0

section() {
  printf '\n[%s]\n' "$1"
}

pass() {
  printf 'PASS %s\n' "$1"
}

warn() {
  printf 'WARN %s\n' "$1"
  warnings=$((warnings + 1))
}

fail() {
  printf 'FAIL %s\n' "$1"
  failures=$((failures + 1))
}

check_file() {
  local path="$1"
  local label="$2"
  if [ -f "$path" ]; then
    pass "$label: $path"
  else
    fail "$label: missing $path"
  fi
}

section "worktree"
if [ -d "$BARON_DIR/.git" ] || [ -f "$BARON_DIR/.git" ]; then
  pass "Baron SSO worktree found: $BARON_DIR"
else
  fail "Baron SSO worktree not found: $BARON_DIR"
fi

check_file "$BARON_DIR/docker-compose.yaml" "compose file"
check_file "$BARON_DIR/.env.sample" "env sample"

section "runtime files"
if [ -f "$BARON_DIR/.env" ]; then
  pass "runtime env file exists"
else
  fail "runtime env file missing (.env)"
  if [ -f "$BARON_DIR/config-restored/env.redacted" ]; then
    warn "redacted env reference exists at config-restored/env.redacted"
  fi
fi

if find "$BARON_DIR/config" -maxdepth 1 -type f ! -name '.gitkeep' | grep -q .; then
  pass "config directory has runtime files"
else
  warn "config directory has no runtime files beyond .gitkeep"
fi

if [ -f "$BARON_DIR/config-restored/compose/docker-compose.yaml" ]; then
  pass "restored compose reference exists"
else
  warn "restored compose reference is missing"
fi

section "docker"
if ! command -v docker >/dev/null 2>&1; then
  warn "docker command not found"
else
  if docker network inspect baron_net >/dev/null 2>&1; then
    pass "docker network baron_net exists"
  else
    warn "docker network baron_net not found or not accessible"
  fi

  if docker network inspect ory-net >/dev/null 2>&1; then
    pass "docker network ory-net exists"
  else
    warn "docker network ory-net not found or not accessible"
  fi

  if docker ps --format '{{.Names}}' 2>/dev/null | grep -qx 'baron_backend'; then
    pass "baron_backend container is running"
  else
    warn "baron_backend container is not running"
  fi

  if docker ps --format '{{.Names}}' 2>/dev/null | grep -qx 'baron_gateway'; then
    pass "baron_gateway container is running"
  else
    warn "baron_gateway container is not running"
  fi
fi

section "next steps"
if [ "$failures" -gt 0 ]; then
  printf 'RESULT blocked: %d failure(s), %d warning(s)\n' "$failures" "$warnings"
  printf 'Hint: create %s/.env from .env.sample and prepare runtime config before API smoke.\n' "$BARON_DIR"
  exit 1
fi

printf 'RESULT ready-ish: %d failure(s), %d warning(s)\n' "$failures" "$warnings"
printf 'Next command example: TDC114_API_BASE=http://127.0.0.1:5000 ./scripts/api-smoke.sh\n'
