#!/usr/bin/env bash
set -Eeuo pipefail

#############################################
# RAG SYSTEM SAFE INSTALLER
# Idempotent • Non-destructive • Production-safe
#############################################

BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$BASE_DIR"

echo "======================================"
echo "RAG System Installer"
echo "Location: $BASE_DIR"
echo "======================================"

#############################################
# Utility
#############################################

fail() {
    echo "ERROR: $1"
    exit 1
}

info() {
    echo "→ $1"
}

command_exists() {
    command -v "$1" >/dev/null 2>&1
}

#############################################
# 1. Project Validation
#############################################

[ -f "composer.json" ] || fail "composer.json not found. Run installer from project root."

[ -f "bin/console" ] || fail "Symfony bin/console not found."

#############################################
# 2. PHP Check
#############################################

command_exists php || fail "PHP not installed."

PHP_VERSION=$(php -r "echo PHP_VERSION;")
PHP_MAJOR=$(php -r "echo PHP_MAJOR_VERSION;")
PHP_MINOR=$(php -r "echo PHP_MINOR_VERSION;")

if [ "$PHP_MAJOR" -lt 8 ] || { [ "$PHP_MAJOR" -eq 8 ] && [ "$PHP_MINOR" -lt 2 ]; }; then
    fail "PHP 8.2+ required. Current: $PHP_VERSION"
fi

info "PHP version OK ($PHP_VERSION)"

#############################################
# 3. Composer Handling (local-safe)
#############################################

if command_exists composer; then
    COMPOSER_BIN="composer"
else
    info "Composer not found globally → installing locally (project only)"
    curl -sS https://getcomposer.org/installer | php >/dev/null
    mv composer.phar composer
    chmod +x composer
    COMPOSER_BIN="$BASE_DIR/composer"
fi

info "Installing PHP dependencies (safe)…"
$COMPOSER_BIN install --no-interaction --prefer-dist --optimize-autoloader

#############################################
# 4. Environment File (non-destructive)
#############################################

if [ ! -f ".env" ]; then
    if [ -f ".env.example" ]; then
        info "Creating .env from .env.example"
        cp .env.example .env
    else
        info "No .env.example found → skipping"
    fi
else
    info ".env already exists → preserved"
fi

#############################################
# 5. Runtime Directories (safe)
#############################################

info "Ensuring runtime directories exist"

mkdir -p var
mkdir -p var/log
mkdir -p var/run
mkdir -p var/vector

#############################################
# 6. Database Migration (safe & conditional)
#############################################

if php bin/console list | grep -q doctrine:migrations:migrate; then
    info "Running database migrations (safe)"
    php bin/console doctrine:migrations:migrate --no-interaction || \
        info "Migration skipped or already applied"
else
    info "Doctrine migrations not detected → skipping"
fi

#############################################
# 7. Python Virtual Environment (idempotent)
#############################################

command_exists python3 || fail "python3 not installed."

VENV_DIR="$BASE_DIR/.venv"

if [ ! -d "$VENV_DIR" ]; then
    info "Creating Python virtual environment"
    python3 -m venv "$VENV_DIR"
else
    info "Using existing Python virtual environment"
fi

PIP="$VENV_DIR/bin/pip"

info "Upgrading pip (safe)"
"$PIP" install --upgrade pip >/dev/null

if [ -f "vector/requirements.txt" ]; then
    info "Installing Python dependencies"
    "$PIP" install -r vector/requirements.txt
else
    info "No vector/requirements.txt found → skipping"
fi

#############################################
# 8. Vector Command Validation
#############################################

if php bin/console list | grep -q mto:agent:vector:control; then
    info "Vector control command detected"
else
    info "Vector control command not found (may be optional)"
fi

#############################################
# 9. Index Validation (non-destructive)
#############################################

if [ -f "var/vector/index.ndjson" ]; then
    info "index.ndjson detected"
else
    info "No index.ndjson yet (normal for fresh install)"
fi

#############################################
# 10. Final Status
#############################################

echo ""
echo "======================================"
echo "INSTALLATION COMPLETE"
echo "======================================"
echo ""
echo "You may now:"
echo ""
echo "  php -S 127.0.0.1:8000 -t public"
echo ""
echo "Vector service:"
echo ""
echo "  php bin/console mto:agent:vector:control --reload"
echo ""
echo "Re-running this installer is safe."
echo ""
echo "======================================"