#!/usr/bin/env bash
#
# Deploys (or redeploys) the application on an already-provisioned VPS.
# Run this as the 'cropai' user, from inside /opt/crop-ai-system, after
# uploading/extracting the project zip there.
#
# Usage: bash deployment/scripts/deploy.sh

set -euo pipefail

APP_DIR="/opt/crop-ai-system"
cd "$APP_DIR"

echo "=== Creating/activating virtual environment ==="
if [ ! -d "venv" ]; then
    python3.12 -m venv venv
fi
source venv/bin/activate

echo "=== Installing dependencies ==="
pip install --upgrade pip
pip install -r requirements.txt

echo "=== Checking .env file exists ==="
if [ ! -f ".env" ]; then
    echo "ERROR: .env file not found at $APP_DIR/.env"
    echo "Copy .env.example to .env and fill in real production values before deploying."
    exit 1
fi

echo "=== Validating model bundle is present ==="
python -m ml_pipeline.evaluation.validate_model_bundle --model-dir data/models/v1

echo "=== Running database migrations ==="
alembic upgrade head

echo "=== Restarting services ==="
sudo systemctl restart crop-ai-api
sudo systemctl restart crop-ai-worker

echo "=== Waiting for API to become ready ==="
sleep 5
for i in $(seq 1 10); do
    if curl -sf http://127.0.0.1:8000/health/ready > /dev/null; then
        echo "API is ready"
        break
    fi
    echo "Waiting for API readiness (attempt $i/10)..."
    sleep 3
done

echo "=== Deployment complete ==="
echo "Check status with:"
echo "  sudo systemctl status crop-ai-api"
echo "  sudo systemctl status crop-ai-worker"
echo "  curl http://127.0.0.1:8000/health/ready"
