#!/usr/bin/env bash
# Development smoke test for FetchML
# 
# NOTE: If using Colima on macOS, ensure the repo directory is mounted:
#   colima stop
#   colima start --mount "/Users/jfraeys/Documents/dev/fetch_ml:w"
#
# Usage:
#   ./scripts/dev/smoke-test.sh                    # Standard run
#   BUILD_PROGRESS=plain ./scripts/dev/smoke-test.sh  # Show full build logs
#   KEEP_STACK=1 ./scripts/dev/smoke-test.sh       # Keep containers after test

set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
export FETCHML_REPO_ROOT="$repo_root"

# Use workspace-relative data directory (Colima-compatible)
# Avoid $HOME/.fetchml - Colima can't create directories through Docker volumes there
DEFAULT_DATA_DIR="$repo_root/data/smoke"
DATA_DIR="${FETCHML_DATA_DIR:-$DEFAULT_DATA_DIR}"

echo "Using DATA_DIR: $DATA_DIR"
rm -rf "$DATA_DIR"

# Create parent directory first with explicit permissions (for Colima compatibility)
mkdir -p "$(dirname "$DATA_DIR")"
chmod 755 "$(dirname "$DATA_DIR")"

# Create data directory structure
mkdir -p "$DATA_DIR"/{redis,minio,logs,experiments,active,workspaces,caddy/data,caddy/config,ssl,configs}
chmod -R 777 "$DATA_DIR"

# Copy configs to DATA_DIR for mounting
cp -r "$repo_root/configs/"* "$DATA_DIR/configs/"

# Build arguments
BUILD_PROGRESS="${BUILD_PROGRESS:-auto}"  # Set to 'plain' for full logs

compose_cmd=$(command -v docker compose >/dev/null 2>&1 && echo "docker compose" || echo "docker-compose")

# Determine build flags
build_flags=""
if [[ "$BUILD_PROGRESS" == "plain" ]]; then
    # For docker compose v2+ with buildkit
    export BUILDKIT_PROGRESS=plain
    build_flags="--progress=plain"
fi

cleanup() {
    status=$?
    if [[ $status -ne 0 ]]; then
        $compose_cmd -f "$repo_root/deployments/docker-compose.dev.yml" logs --no-color 2>/dev/null || true
    fi
    if [[ "${KEEP_STACK:-0}" != "1" ]]; then
        $compose_cmd -f "$repo_root/deployments/docker-compose.dev.yml" down -v >/dev/null 2>&1 || true
        rm -rf "$DATA_DIR"
    fi
    exit $status
}

trap cleanup EXIT

echo "Starting dev stack for smoke test..."
export DATA_DIR="$DATA_DIR"

# Build first with progress option if specified, then up
if [[ "$BUILD_PROGRESS" == "plain" ]]; then
    $compose_cmd -f "$repo_root/deployments/docker-compose.dev.yml" --project-directory "$repo_root" build --progress=plain
fi
$compose_cmd -f "$repo_root/deployments/docker-compose.dev.yml" --project-directory "$repo_root" up -d --build

echo "Waiting for API to become healthy..."
deadline=$(( $(date +%s) + 180 ))
while ! curl -sf http://localhost:9101/health >/dev/null 2>&1; do
    if [[ $(date +%s) -ge $deadline ]]; then
        echo "Timed out waiting for API"
        exit 1
    fi
    sleep 2
done

echo "API is healthy"