#!/bin/bash
# =============================================================================
# TFM aInventory - Bulletproof Deployment Script (v1.9.12)
# =============================================================================

set -e

# Load environment variables (from root inventory.env)
if [ -f inventory.env ]; then
    export $(grep -v '^#' inventory.env | xargs)
    echo "✅ Loaded configuration from inventory.env"
else
    echo "⚠️  inventory.env not found. Using default values."
fi

# Parse arguments
RESET_SSL=false
RESET_ADMIN=false

for arg in "$@"; do
    case $arg in
        --reset-ssl)
            RESET_SSL=true
            shift
            ;;
        --reset-admin)
            RESET_ADMIN=true
            shift
            ;;
        --help)
            echo "Usage: ./deploy.sh [options]"
            echo "Options:"
            echo "  --reset-ssl    Clear Caddy storage and reset certificates (Aggressive)"
            echo "  --reset-admin  Force reset Admin password to 'Admin123!'"
            echo "  --help         Show this help message"
            exit 0
            ;;
    esac
done

if [ "$RESET_SSL" = true ]; then
    echo "🧹 Aggressive SSL Reset in progress..."
    docker compose down
    # Clear internal docker volumes
    docker volume rm -f inventory_caddy_data 2>/dev/null || true
    docker volume rm -f inventory_caddy_config 2>/dev/null || true
    # Clear persistent host volumes if they exist
    rm -rf ./data/caddy_data/* 2>/dev/null || true
    rm -rf ./data/caddy_config/* 2>/dev/null || true
    echo "✅ SSL storage completely cleared."
fi

echo "🚀 Starting TFM aInventory Services..."
# Use --build to ensure the custom Caddy image is built
docker compose --env-file inventory.env up -d --build --remove-orphans

if [ "$RESET_ADMIN" = true ]; then
    echo "🔐 Resetting Admin credentials..."
    # Wait for container to be ready
    sleep 3
    docker compose exec backend python3 -m backend.scripts.reset_admin
fi

echo ""
echo "🔍 Verifying port mapping..."
docker compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"

echo ""
echo "🚀 DIAGNOSTIC LOGS (Proxy Status):"
docker compose logs proxy --tail 20

echo ""
echo "✅ Deployment complete (v1.9.12)."
echo "   ------------------------------------------------------------"
echo "   ACCESS COORDINATES:"
echo "   1. SECURE: https://${SERVER_IP:-localhost}:${FRONTEND_SSL_PORT:-8919}"
echo "   2. DIRECT: http://${SERVER_IP:-localhost}:${FRONTEND_PORT:-8917}"
echo "   ------------------------------------------------------------"
echo "   CREDENTIALS (if first run or reset):"
echo "   User: Admin"
echo "   Pass: Admin123!"
echo "   ------------------------------------------------------------"
echo ""
