#!/bin/bash
# AI WRITTEN
set -e

# Ensure we run from the script's directory
cd "$(dirname "$0")"

# Load environment variables if they exist
if [ -f .env ]; then
    set -a
    source .env
    set +a
fi

echo "Wiping database volume and restarting containers..."
docker compose -f docker-compose-dev.yml down -v
docker compose -f docker-compose-dev.yml up -d

echo "Waiting for PostgreSQL to be ready..."
until [ "$(docker inspect -f '{{.State.Health.Status}}' tg-dev-srv-bot-postgres 2>/dev/null)" = "healthy" ]; do
    printf "."
    sleep 1
done
echo ""
echo "PostgreSQL is healthy!"

echo "Applying database schema from sqlschema.txt..."
docker compose -f docker-compose-dev.yml exec -T postgres psql -U "${TG_BOT_POSTGRES_USER:-postgres}" -d "${TG_BOT_POSTGRES_DB:-tg_dev_srv_bot}" -c "$(cat sqlschema.txt)"

echo "Database reset and schema applied successfully!"