#!/bin/bash
# StemeDB Demo - One-Command Setup
#
# This script:
# 1. Builds the StemeDB API (if needed)
# 2. Starts the API server in the background
# 3. Waits for health check
# 4. Seeds demo data with realistic agent names
# 5. Opens the dashboard in your browser
#
# Usage:
#   ./scripts/run-demo.sh
#   ./scripts/run-demo.sh --no-open  # Don't open browser
#   ./scripts/run-demo.sh --clean    # Start fresh (delete existing data)

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# Configuration
API_PORT="${STEMEDB_PORT:-18180}"
DASHBOARD_PORT="${DASHBOARD_PORT:-18188}"
DATA_DIR="${STEMEDB_DATA_DIR:-$PROJECT_ROOT/data/demo}"
API_PID_FILE="$DATA_DIR/.api.pid"
OPEN_BROWSER=true
CLEAN_START=false

# Parse arguments
for arg in "$@"; do
    case $arg in
        --no-open)
            OPEN_BROWSER=false
            shift
            ;;
        --clean)
            CLEAN_START=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [--no-open] [--clean]"
            echo ""
            echo "Options:"
            echo "  --no-open  Don't open browser after starting"
            echo "  --clean    Delete existing data and start fresh"
            echo ""
            exit 0
            ;;
    esac
done

# Helper functions
print_header() {
    echo -e "\n${BOLD}${BLUE}$1${NC}"
    echo -e "${BLUE}$(printf '=%.0s' {1..60})${NC}\n"
}

print_step() {
    echo -e "${CYAN}=> $1${NC}"
}

print_success() {
    echo -e "${GREEN}[OK] $1${NC}"
}

print_error() {
    echo -e "${RED}[ERROR] $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}[WARN] $1${NC}"
}

cleanup() {
    if [ -f "$API_PID_FILE" ]; then
        API_PID=$(cat "$API_PID_FILE")
        if kill -0 "$API_PID" 2>/dev/null; then
            print_step "Stopping StemeDB API (PID: $API_PID)..."
            kill "$API_PID" 2>/dev/null || true
        fi
        rm -f "$API_PID_FILE"
    fi
}

# Set up cleanup on exit
trap cleanup EXIT

# ============================================================================
# MAIN
# ============================================================================

print_header "StemeDB Demo Setup"

echo -e "${BOLD}Configuration:${NC}"
echo "  Project Root: $PROJECT_ROOT"
echo "  API Port: $API_PORT"
echo "  Dashboard Port: $DASHBOARD_PORT"
echo "  Data Directory: $DATA_DIR"
echo ""

cd "$PROJECT_ROOT"

# Create data directory
mkdir -p "$DATA_DIR"

# Clean start if requested
if [ "$CLEAN_START" = true ]; then
    print_step "Cleaning existing data..."
    rm -rf "$DATA_DIR"/*
    print_success "Data cleaned"
fi

# ============================================================================
# Step 1: Build StemeDB API
# ============================================================================

print_header "Step 1: Building StemeDB API"

if [ ! -f "$PROJECT_ROOT/target/release/stemedb-api" ]; then
    print_step "Building release binary..."
    cargo build --release --package stemedb-api
    print_success "Build complete"
else
    print_step "Checking if rebuild needed..."
    # Check if source is newer than binary
    SRC_TIME=$(find crates -name "*.rs" -newer target/release/stemedb-api 2>/dev/null | head -1)
    if [ -n "$SRC_TIME" ]; then
        print_step "Source changed, rebuilding..."
        cargo build --release --package stemedb-api
        print_success "Rebuild complete"
    else
        print_success "Binary is up to date"
    fi
fi

# ============================================================================
# Step 2: Start StemeDB API
# ============================================================================

print_header "Step 2: Starting StemeDB API"

# Check if already running
if [ -f "$API_PID_FILE" ]; then
    OLD_PID=$(cat "$API_PID_FILE")
    if kill -0 "$OLD_PID" 2>/dev/null; then
        print_warning "StemeDB API already running (PID: $OLD_PID)"
        print_step "Stopping existing instance..."
        kill "$OLD_PID" 2>/dev/null || true
        sleep 1
    fi
    rm -f "$API_PID_FILE"
fi

print_step "Starting StemeDB API on port $API_PORT..."

# Set environment variables for demo
export STEMEDB_BIND_ADDR="127.0.0.1:$API_PORT"
export STEMEDB_DATA_DIR="$DATA_DIR"
export RUST_LOG="${RUST_LOG:-info}"

# Start API in background
"$PROJECT_ROOT/target/release/stemedb-api" > "$DATA_DIR/api.log" 2>&1 &
API_PID=$!
echo "$API_PID" > "$API_PID_FILE"

print_success "API started (PID: $API_PID)"
echo "  Log file: $DATA_DIR/api.log"

# ============================================================================
# Step 3: Wait for Health Check
# ============================================================================

print_header "Step 3: Waiting for API Health"

MAX_ATTEMPTS=30
ATTEMPT=0

while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
    ATTEMPT=$((ATTEMPT + 1))

    if curl -s "http://localhost:$API_PORT/v1/health" > /dev/null 2>&1; then
        print_success "API is healthy"
        break
    fi

    if ! kill -0 "$API_PID" 2>/dev/null; then
        print_error "API process died. Check logs:"
        echo "  tail -50 $DATA_DIR/api.log"
        exit 1
    fi

    echo -ne "\r  Waiting... ($ATTEMPT/$MAX_ATTEMPTS)"
    sleep 1
done

if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
    print_error "API failed to become healthy after ${MAX_ATTEMPTS}s"
    echo "  Check logs: tail -50 $DATA_DIR/api.log"
    exit 1
fi

echo ""

# ============================================================================
# Step 4: Seed Demo Data
# ============================================================================

print_header "Step 4: Seeding Demo Data"

print_step "Running demo-seed..."
echo ""

cd "$PROJECT_ROOT/cmd/demo-seed"
go run . --api-url "http://localhost:$API_PORT" --keys-file "$PROJECT_ROOT/demo/keys/agents.json"

print_success "Demo data seeded"

# ============================================================================
# Step 5: Open Dashboard
# ============================================================================

print_header "Step 5: Dashboard Ready"

DASHBOARD_URL="http://localhost:$DASHBOARD_PORT"
API_URL="http://localhost:$API_PORT"

echo -e "${BOLD}Demo URLs:${NC}"
echo -e "  API:        ${CYAN}$API_URL${NC}"
echo -e "  Dashboard:  ${CYAN}$DASHBOARD_URL${NC}"
echo ""

echo -e "${BOLD}Quick Links:${NC}"
echo -e "  Skeptic Query:  ${CYAN}$DASHBOARD_URL/skeptic${NC}"
echo -e "  Audit Trail:    ${CYAN}$DASHBOARD_URL/audit${NC}"
echo -e "  Quarantine:     ${CYAN}$DASHBOARD_URL/quarantine${NC}"
echo ""

echo -e "${BOLD}Try These API Queries:${NC}"
echo -e "  ${YELLOW}curl -s '$API_URL/v1/skeptic?subject=semaglutide:gastroparesis_risk&predicate=risk_level' | jq${NC}"
echo -e "  ${YELLOW}curl -s '$API_URL/v1/layered?subject=semaglutide:gastroparesis_risk&predicate=risk_level' | jq${NC}"
echo -e "  ${YELLOW}curl -s '$API_URL/v1/admin/quarantine?limit=10' | jq${NC}"
echo ""

if [ "$OPEN_BROWSER" = true ]; then
    print_step "Opening dashboard..."

    # Try different methods to open browser
    if command -v open &> /dev/null; then
        open "$DASHBOARD_URL" 2>/dev/null || true
    elif command -v xdg-open &> /dev/null; then
        xdg-open "$DASHBOARD_URL" 2>/dev/null || true
    else
        print_warning "Could not detect browser. Open manually: $DASHBOARD_URL"
    fi
fi

# ============================================================================
# Keep Running
# ============================================================================

print_header "Demo Running"

echo -e "${GREEN}${BOLD}StemeDB demo is running!${NC}"
echo ""
echo "Press Ctrl+C to stop the server."
echo ""
echo "Logs: tail -f $DATA_DIR/api.log"
echo ""

# Wait for API process
wait "$API_PID"
