#!/bin/bash
# Comprehensive Database Setup Script for Foxhunt HFT System
# This script sets up PostgreSQL, runs migrations, and prepares SQLx for offline compilation

set -e

echo "🚀 Setting up Foxhunt HFT Database..."

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if Docker is available
if command -v docker >/dev/null 2>&1 && command -v docker-compose >/dev/null 2>&1; then
    echo -e "${GREEN}✅ Docker and docker-compose found${NC}"
    USE_DOCKER=true
else
    echo -e "${YELLOW}⚠️  Docker not found, will attempt local setup${NC}"
    USE_DOCKER=false
fi

if [ "$USE_DOCKER" = true ]; then
    echo -e "${GREEN}📦 Starting PostgreSQL with Docker...${NC}"

    # Start PostgreSQL with docker-compose
    docker-compose -f docker-compose.dev.yml up -d postgres

    # Wait for PostgreSQL to be ready
    echo "⏳ Waiting for PostgreSQL to be ready..."
    for i in {1..30}; do
        if docker-compose -f docker-compose.dev.yml exec -T postgres pg_isready -U foxhunt -d foxhunt >/dev/null 2>&1; then
            echo -e "${GREEN}✅ PostgreSQL is ready!${NC}"
            break
        fi
        echo "Waiting... ($i/30)"
        sleep 2
    done

    # Set DATABASE_URL for Docker setup
    export DATABASE_URL="postgresql://foxhunt:foxhunt_dev_password@localhost:5432/foxhunt"

else
    echo -e "${YELLOW}🔧 Setting up local PostgreSQL...${NC}"

    # Check if PostgreSQL is installed
    if ! command -v psql >/dev/null 2>&1; then
        echo -e "${RED}❌ PostgreSQL client not found. Please install PostgreSQL.${NC}"
        exit 1
    fi

    # Try to connect to local PostgreSQL
    export DATABASE_URL="postgresql://localhost/foxhunt"

    # Create database if it doesn't exist
    echo "Creating database..."
    createdb foxhunt 2>/dev/null || echo "Database may already exist"

    # Run init-db.sql
    echo "Running initial database setup..."
    psql -d foxhunt -f scripts/init-db.sql

    # Run migrations in order
    echo "Running migrations..."
    for migration in migrations/0*.sql; do
        if [[ -f "$migration" ]]; then
            echo "Running: $migration"
            psql -d foxhunt -f "$migration"
        fi
    done
fi

# Update .env file with correct DATABASE_URL
echo -e "${GREEN}📝 Updating .env file...${NC}"
if [ -f .env ]; then
    # Create backup of .env
    cp .env .env.backup

    # Update DATABASE_URL in .env
    if [ "$USE_DOCKER" = true ]; then
        sed -i 's|DATABASE_URL=.*|DATABASE_URL=postgresql://foxhunt:foxhunt_dev_password@localhost:5432/foxhunt|' .env
    else
        sed -i 's|DATABASE_URL=.*|DATABASE_URL=postgresql://localhost/foxhunt|' .env
    fi

    echo -e "${GREEN}✅ Updated DATABASE_URL in .env${NC}"
fi

# Generate SQLx metadata
echo -e "${GREEN}🔧 Generating SQLx metadata...${NC}"
if cargo sqlx prepare; then
    echo -e "${GREEN}✅ SQLx metadata generated successfully!${NC}"
else
    echo -e "${YELLOW}⚠️  SQLx prepare failed, but continuing...${NC}"
fi

# Test compilation
echo -e "${GREEN}🏗️  Testing compilation...${NC}"
if SQLX_OFFLINE=true cargo check --workspace --quiet; then
    echo -e "${GREEN}✅ Compilation successful!${NC}"
else
    echo -e "${YELLOW}⚠️  Some compilation issues remain (this may be expected)${NC}"
fi

echo ""
echo -e "${GREEN}🎉 Database setup complete!${NC}"
echo ""
echo "Next steps:"
echo "1. Your database is now set up and migrations have been applied"
echo "2. SQLx should now work for compile-time verification"
echo "3. You can start the services with: cargo run --bin trading-service"
echo ""
echo "Database connection details:"
echo "  URL: $DATABASE_URL"
if [ "$USE_DOCKER" = true ]; then
    echo "  To stop: docker-compose -f docker-compose.dev.yml down"
    echo "  To connect: docker-compose -f docker-compose.dev.yml exec postgres psql -U foxhunt -d foxhunt"
else
    echo "  To connect: psql -d foxhunt"
fi