#!/bin/bash

# AI Trip Planner Laravel Backend - Universal Docker Setup Script
# This script works with both docker-compose and podman-compose

set -e

echo "🚀 Setting up AI Trip Planner Laravel Backend with Docker/Podman..."

# Detect which compose tool is available
COMPOSE_CMD=""
if command -v docker-compose &> /dev/null; then
    COMPOSE_CMD="docker-compose"
    echo "✅ Using docker-compose"
elif command -v podman-compose &> /dev/null; then
    COMPOSE_CMD="podman-compose"
    echo "✅ Using podman-compose"
elif command -v docker &> /dev/null && docker compose version &> /dev/null; then
    COMPOSE_CMD="docker compose"
    echo "✅ Using docker compose (v2)"
else
    echo "❌ Neither docker-compose nor podman-compose is installed."
    echo "Please install Docker/Podman and Docker Compose first."
    exit 1
fi

# Clean up existing containers first
echo "🧹 Cleaning up existing containers..."
if [ -f "./cleanup.sh" ]; then
    ./cleanup.sh
else
    echo "Stopping and removing existing containers..."
    $COMPOSE_CMD down --remove-orphans 2>/dev/null || true
fi

# Create .env file from .env.docker if it doesn't exist
if [ ! -f ../.env ]; then
    echo "📝 Creating .env file from .env.docker template..."
    if [ -f .env.docker ]; then
        cp .env.docker ../.env
    elif [ -f .env.docker.sample ]; then
        cp .env.docker.sample ../.env
    else
        echo "❌ No .env template found. Please create ../.env manually."
        exit 1
    fi
    echo "⚠️  Please edit ../.env and add your API keys before continuing!"
    echo "   Required API keys:"
    echo "   - OPENAI_API_KEY"
    echo "   - LITEAPI_API_KEY"
    echo "   - ACTIVITYLINKER_API_KEY"
    echo "   - DUFFEL_API_TOKEN"
    echo ""
    read -p "Press Enter after you've updated the API keys in ../.env..."
fi

# Build and start the containers
echo "🏗️  Building Docker containers..."
$COMPOSE_CMD build --no-cache

echo "🚀 Starting Docker containers..."
$COMPOSE_CMD up -d

# Wait for database to be ready
echo "⏳ Waiting for database to be ready..."
sleep 30

# Clear Laravel cache files that might contain dev dependencies
echo "🧹 Clearing Laravel cache files..."
$COMPOSE_CMD exec app rm -f /var/www/bootstrap/cache/packages.php
$COMPOSE_CMD exec app rm -f /var/www/bootstrap/cache/services.php
$COMPOSE_CMD exec app rm -f /var/www/bootstrap/cache/config.php

# Generate Laravel application key
echo "🔑 Generating Laravel application key..."
$COMPOSE_CMD exec app php artisan key:generate --force

# Run database migrations
echo "📊 Running database migrations..."
$COMPOSE_CMD exec app php artisan migrate --force

# Set proper permissions
echo "🔒 Setting proper permissions..."
$COMPOSE_CMD exec app chown -R www-data:www-data /var/www/storage
$COMPOSE_CMD exec app chown -R www-data:www-data /var/www/bootstrap/cache
$COMPOSE_CMD exec app chmod -R 755 /var/www/storage
$COMPOSE_CMD exec app chmod -R 755 /var/www/bootstrap/cache

# Clear and cache configuration
echo "🧹 Clearing and caching configuration..."
$COMPOSE_CMD exec app php artisan config:clear
$COMPOSE_CMD exec app php artisan config:cache
$COMPOSE_CMD exec app php artisan route:cache
$COMPOSE_CMD exec app php artisan view:cache

echo ""
echo "✅ Setup complete!"
echo ""
echo "🌐 Your AI Trip Planner Laravel Backend is now running at:"
echo "   http://localhost:8000"
echo ""
echo "📊 Database is accessible at:"
echo "   Host: localhost"
echo "   Port: 3307 (mapped from container port 3306)"
echo "   Database: ai_trip_planner"
echo "   Username: laravel"
echo "   Password: secret"
echo ""
echo "🔴 Redis is accessible at:"
echo "   Host: localhost"
echo "   Port: 6380 (mapped from container port 6379)"
echo ""
echo "🔧 Useful commands:"
echo "   View logs: $COMPOSE_CMD logs -f"
echo "   Stop containers: $COMPOSE_CMD down"
echo "   Restart containers: $COMPOSE_CMD restart"
echo "   Access app container: $COMPOSE_CMD exec app bash"
echo "   Run artisan commands: $COMPOSE_CMD exec app php artisan <command>"
echo "   Clean up everything: ./cleanup.sh"
echo ""
echo "🧪 Test the API:"
echo "   curl http://localhost:8000/api/health"
echo ""
