#!/bin/bash
# PostgreSQL Setup Script for Trax Development
# This script helps set up PostgreSQL locally for development

set -e

echo "🐘 PostgreSQL Setup for Trax Development"
echo "========================================"

# Check if PostgreSQL is installed
if ! command -v psql &> /dev/null; then
    echo "❌ PostgreSQL is not installed."
    echo ""
    echo "📦 Installation Options:"
    echo "1. macOS (using Homebrew): brew install postgresql@14"
    echo "2. Ubuntu/Debian: sudo apt-get install postgresql-14"
    echo "3. CentOS/RHEL: sudo yum install postgresql14-server"
    echo "4. Windows: Download from https://www.postgresql.org/download/windows/"
    echo ""
    echo "After installation, run this script again."
    exit 1
fi

echo "✅ PostgreSQL is installed"

# Check if PostgreSQL service is running
if ! pg_isready -q; then
    echo "⚠️  PostgreSQL service is not running."
    echo ""
    echo "🚀 Starting PostgreSQL service..."
    
    # Try to start PostgreSQL (platform-specific)
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # macOS
        if command -v brew &> /dev/null; then
            brew services start postgresql@14 || brew services start postgresql
        else
            echo "❌ Please start PostgreSQL manually or install via Homebrew"
            exit 1
        fi
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        # Linux
        sudo systemctl start postgresql || sudo service postgresql start
    else
        echo "❌ Please start PostgreSQL manually for your platform"
        exit 1
    fi
    
    # Wait a moment for the service to start
    sleep 3
fi

echo "✅ PostgreSQL service is running"

# Check if trax database exists
if psql -lqt | cut -d \| -f 1 | grep -qw trax; then
    echo "✅ Database 'trax' already exists"
else
    echo "📊 Creating database 'trax'..."
    
    # Try to create database as current user first
    if createdb trax 2>/dev/null; then
        echo "✅ Database 'trax' created successfully"
    else
        echo "⚠️  Could not create database as current user"
        echo "   Trying with postgres user..."
        
        # Try with postgres user
        if sudo -u postgres createdb trax 2>/dev/null; then
            echo "✅ Database 'trax' created successfully with postgres user"
        else
            echo "❌ Could not create database 'trax'"
            echo ""
            echo "🔧 Manual Setup Required:"
            echo "1. Connect to PostgreSQL as superuser:"
            echo "   sudo -u postgres psql"
            echo "2. Create database:"
            echo "   CREATE DATABASE trax;"
            echo "3. Create user (optional):"
            echo "   CREATE USER trax_user WITH PASSWORD 'your_password';"
            echo "   GRANT ALL PRIVILEGES ON DATABASE trax TO trax_user;"
            echo "4. Exit:"
            echo "   \\q"
            exit 1
        fi
    fi
fi

# Test connection
echo "🔌 Testing database connection..."
if psql -d trax -c "SELECT version();" > /dev/null 2>&1; then
    echo "✅ Database connection successful"
else
    echo "❌ Database connection failed"
    echo ""
    echo "🔧 Troubleshooting:"
    echo "1. Check if PostgreSQL is running: pg_isready"
    echo "2. Check database exists: psql -l"
    echo "3. Test connection: psql -d trax"
    exit 1
fi

# Enable JSONB extension (should be enabled by default in PostgreSQL 9.4+)
echo "🔧 Checking JSONB support..."
if psql -d trax -c "SELECT 'jsonb'::regtype;" > /dev/null 2>&1; then
    echo "✅ JSONB support is available"
else
    echo "❌ JSONB support not available"
    echo "   This might indicate an older PostgreSQL version"
    echo "   JSONB requires PostgreSQL 9.4 or later"
    exit 1
fi

echo ""
echo "🎉 PostgreSQL setup completed successfully!"
echo ""
echo "📋 Next Steps:"
echo "1. Run the database test: uv run python test_database_setup.py"
echo "2. Create initial migration: uv run alembic revision --autogenerate -m 'Initial schema'"
echo "3. Apply migration: uv run alembic upgrade head"
echo ""
echo "🔧 Configuration:"
echo "   Database URL: postgresql://localhost/trax"
echo "   Database Name: trax"
echo "   Host: localhost"
echo "   Port: 5432"
