#!/bin/bash
# Smart database reload - only swaps if DB_DUMP changed
#
# Tracks which dump is currently loaded and only reloads if different.
# Edit DB_DUMP in .env and run this script - it handles the rest.
#
# Usage:
#   ./reload-db.sh           # Reload if DB_DUMP changed
#   ./reload-db.sh --force   # Force reload even if same

set -e

cd "$(dirname "$0")/../.."

FORCE=false
if [ "$1" = "--force" ]; then
    FORCE=true
fi

# Get config from .env
DEPLOYMENT_NAME=$(grep "^DEPLOYMENT_NAME=" .env 2>/dev/null | cut -d'=' -f2 || echo "amar")
POSTGRES_DB=$(grep "^POSTGRES_DB=" .env 2>/dev/null | cut -d'=' -f2 || echo "amarback")
POSTGRES_USER=$(grep "^POSTGRES_USER=" .env 2>/dev/null | cut -d'=' -f2 || echo "postgres")
DB_DUMP=$(grep "^DB_DUMP=" .env 2>/dev/null | cut -d'=' -f2)

if [ -z "$DB_DUMP" ]; then
    echo "Error: DB_DUMP not set in .env"
    echo ""
    echo "Add to .env:"
    echo "  DB_DUMP=dev.sql"
    echo ""
    echo "Available dumps:"
    ls -1 dumps/*.sql 2>/dev/null | sed 's/dumps\//  /' || echo "  No dumps found in dumps/"
    exit 1
fi

DUMP_FILE="dumps/${DB_DUMP}"
if [ ! -f "$DUMP_FILE" ]; then
    echo "Error: Dump file not found: $DUMP_FILE"
    echo ""
    echo "Available dumps:"
    ls -1 dumps/*.sql 2>/dev/null | sed 's/dumps\//  /' || echo "  No dumps found in dumps/"
    exit 1
fi

DB_CONTAINER="${DEPLOYMENT_NAME}_db"
BACKEND_CONTAINER="${DEPLOYMENT_NAME}_backend"
STATE_FILE=".db_state"

# Check if db container is running
if ! docker ps --format "{{.Names}}" | grep -q "^${DB_CONTAINER}$"; then
    echo "Error: Database container not running: $DB_CONTAINER"
    echo "Start services first with: ./ctrl/start.sh -d"
    exit 1
fi

# Check current state
if [ -f "$STATE_FILE" ] && [ "$FORCE" = false ]; then
    CURRENT_DUMP=$(cat "$STATE_FILE")
    if [ "$CURRENT_DUMP" = "$DB_DUMP" ]; then
        echo "Database already loaded with: $DB_DUMP"
        echo "Use --force to reload anyway"
        exit 0
    fi
    echo "Database dump changed: $CURRENT_DUMP → $DB_DUMP"
else
    if [ "$FORCE" = true ]; then
        echo "Force reloading database with: $DB_DUMP"
    else
        echo "Loading database with: $DB_DUMP"
    fi
fi

echo ""
read -p "Continue with database reload? (y/N) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 0
fi

echo ""
echo "[1/5] Stopping backend and celery services..."
docker compose stop backend celery celery-beat 2>/dev/null || true

echo ""
echo "[2/5] Dropping and recreating database..."
docker exec "$DB_CONTAINER" psql -U "$POSTGRES_USER" -d postgres -c "DROP DATABASE IF EXISTS $POSTGRES_DB WITH (FORCE);"
docker exec "$DB_CONTAINER" psql -U "$POSTGRES_USER" -d postgres -c "CREATE DATABASE $POSTGRES_DB;"
docker exec "$DB_CONTAINER" psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE EXTENSION IF NOT EXISTS postgis_topology;"

echo ""
echo "[3/5] Loading dump: $DB_DUMP..."
docker exec -i "$DB_CONTAINER" psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" < "$DUMP_FILE"

echo ""
echo "[4/5] Restarting services and running migrations..."
docker compose start backend celery celery-beat

echo "Waiting for backend to start..."
sleep 3

echo "Running migrations..."
docker exec "$BACKEND_CONTAINER" python manage.py migrate --noinput

echo ""
echo "[5/5] Updating state..."
echo "$DB_DUMP" > "$STATE_FILE"

echo ""
echo "=========================================="
echo "  Database Reloaded Successfully"
echo "=========================================="
echo ""
echo "Current dump: $DB_DUMP"
echo "Database: $POSTGRES_DB"
echo ""
