#!/usr/bin/env bash
# Automated morning health check for the project environment
set -euo pipefail

# 1. Disk Cleanup Check
echo "--- Checking Disk Usage ---"
DISK_USAGE=$(df / --output=pcent | tail -1 | tr -dc '0-9')
if [ "$DISK_USAGE" -gt 80 ]; then
    echo "WARN: Disk usage is at ${DISK_USAGE}%. Running cleanup..."
    docker system prune -f --volumes || true
    rm -rf var/cache/* || true
else
    echo "OK: Disk usage at ${DISK_USAGE}%."
fi

# 2. Dependency Synchronization Check
echo "--- Checking Dependencies ---"
if [ -f "composer.json" ]; then
    if [ ! -d "vendor" ] || [ "composer.json" -nt "vendor/autoload.php" ]; then
        echo "WARN: Dependencies out of sync. Running composer install..."
        composer install --ignore-platform-req=ext-firebird || echo "WARN: composer install failed. Please check platform requirements."
    else
        echo "OK: Composer dependencies up to date."
    fi
fi

if [ -f "package.json" ]; then
    if [ ! -d "node_modules" ]; then
         # Check if pnpm or npm should be used
         if [ -f "pnpm-lock.yaml" ]; then
             echo "WARN: pnpm dependencies might be out of sync. Running pnpm install..."
             pnpm install --frozen-lockfile || echo "WARN: pnpm install failed."
         else
             echo "WARN: npm dependencies missing. Running npm install..."
             npm install || echo "WARN: npm install failed."
         fi
    else
        echo "OK: Frontend dependencies appear up to date."
    fi
fi

# 3. Git Fetch
echo "--- Fetching Latest Changes ---"
git fetch origin --quiet && echo "OK: Git origin fetched." || echo "WARN: Could not fetch from origin."

# 4. Docker & DB Health Check
echo "--- Checking Docker & DB ---"
if docker compose ps > /dev/null 2>&1; then
    RUNNING_CONTAINERS=$(docker compose ps --format '{{.Status}}' | grep -c "Up" || true)
    if [ "$RUNNING_CONTAINERS" -gt 0 ]; then
        echo "OK: Docker containers are running ($RUNNING_CONTAINERS containers Up)."
        
        # Check DB accessibility (Firebird in this project)
        if docker compose exec -T firebird_server echo "DB container responsive" > /dev/null 2>&1; then
             echo "OK: Database container is responsive."
        else
             echo "WARN: Database container is NOT responsive."
        fi
    else
        echo "WARN: No Docker containers are running. Run 'docker compose up -d'."
    fi
else
    echo "WARN: Docker Compose not initialized or failed to run."
fi

echo "--- Health Check Complete ---"
