#!/bin/bash

# Memento Docker Deployment Script
# This script helps you build and deploy Memento on Proxmox/Docker

set -e

echo "🚀 Memento Docker Deployment"
echo "================================"
echo ""

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo -e "${RED}❌ Docker is not installed${NC}"
    echo "Please install Docker first: https://docs.docker.com/get-docker/"
    exit 1
fi

# Check if docker compose is available (modern Docker Compose v2)
if ! docker compose version &> /dev/null; then
    echo -e "${RED}❌ Docker Compose is not installed${NC}"
    echo "Please install Docker Compose first"
    exit 1
fi

echo -e "${GREEN}✓ Docker and Docker Compose found${NC}"
echo ""

# Check if .env exists
if [ ! -f .env ]; then
    echo -e "${YELLOW}⚠️  .env file not found${NC}"
    echo "Creating .env file with defaults..."

    # Generate random secret
    SECRET=$(openssl rand -base64 32 2>/dev/null || echo "change-this-secret-in-production")

    cat > .env << EOF
# Required: Application Configuration
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=$SECRET

# Optional: OpenAI API Key (uncomment to use)
# OPENAI_API_KEY=sk-your-key-here

# Optional: Ollama Configuration (uncomment to use local AI)
# OLLAMA_BASE_URL=http://ollama:11434
# OLLAMA_MODEL=granite4:latest
EOF

    echo -e "${GREEN}✓ .env file created${NC}"
    echo ""
    echo -e "${YELLOW}⚠️  IMPORTANT: Edit .env and update NEXTAUTH_URL and NEXTAUTH_SECRET${NC}"
    read -p "Press Enter to continue after editing .env..."
fi

# Parse command line arguments
COMMAND=${1:-"help"}

case $COMMAND in
    build)
        echo "🔨 Building Docker image..."
        docker compose build
        echo -e "${GREEN}✓ Build completed${NC}"
        ;;

    start|up)
        echo "🚀 Starting containers..."
        docker compose up -d
        echo -e "${GREEN}✓ Containers started${NC}"
        echo ""
        echo "📝 Application available at: http://localhost:3000"
        ;;

    stop|down)
        echo "⏹️  Stopping containers..."
        docker compose down
        echo -e "${GREEN}✓ Containers stopped${NC}"
        ;;

    restart)
        echo "🔄 Restarting containers..."
        docker compose restart
        echo -e "${GREEN}✓ Containers restarted${NC}"
        ;;

    logs)
        echo "📋 Showing logs (Ctrl+C to exit)..."
        docker compose logs -f memento-note
        ;;

    status)
        echo "📊 Container status:"
        docker compose ps
        ;;

    update)
        echo "🔄 Updating application..."
        echo "Pulling latest changes..."
        git pull
        echo "Rebuilding..."
        docker compose build
        echo "Restarting..."
        docker compose down
        docker compose up -d
        echo -e "${GREEN}✓ Update completed${NC}"
        ;;

    backup)
        echo "💾 Creating database backup..."
        BACKUP_DIR="./backups"
        mkdir -p $BACKUP_DIR
        DATE=$(date +%Y%m%d_%H%M%S)

        docker exec memento-note \
            cp /app/prisma/dev.db /app/prisma/backup_$DATE.db 2>/dev/null || {
            echo -e "${RED}❌ Container not running. Start it first with: $0 start${NC}"
            exit 1
        }

        docker cp memento-note:/app/prisma/backup_$DATE.db \
            $BACKUP_DIR/memento-note_$DATE.db

        echo -e "${GREEN}✓ Backup created: $BACKUP_DIR/memento-note_$DATE.db${NC}"
        ;;

    clean)
        echo "🧹 Cleaning up..."
        echo "Stopping containers..."
        docker compose down
        echo "Removing old images..."
        docker image prune -a -f
        echo "Removing unused volumes..."
        docker volume prune -f
        echo -e "${GREEN}✓ Cleanup completed${NC}"
        ;;

    ollama-pull)
        MODEL=${2:-"granite4"}
        echo "🤖 Pulling Ollama model: $MODEL"
        docker compose exec -it ollama ollama pull $MODEL
        echo -e "${GREEN}✓ Model pulled${NC}"
        ;;

    shell)
        echo "🐚 Opening shell in container..."
        docker compose exec memento-note sh
        ;;

    *)
        echo "Usage: $0 {build|start|stop|restart|logs|status|update|backup|clean|ollama-pull|shell}"
        echo ""
        echo "Commands:"
        echo "  build          - Build Docker image"
        echo "  start, up      - Start containers"
        echo "  stop, down     - Stop containers"
        echo "  restart        - Restart containers"
        echo "  logs           - Show container logs"
        echo "  status         - Show container status"
        echo "  update         - Pull latest, rebuild, and restart"
        echo "  backup         - Backup database"
        echo "  clean          - Remove containers, images, and volumes"
        echo "  ollama-pull    - Pull Ollama model (optional: model name)"
        echo "  shell          - Open shell in container"
        echo ""
        echo "Examples:"
        echo "  $0 build"
        echo "  $0 start"
        echo "  $0 logs"
        echo "  $0 update"
        echo "  $0 ollama-pull llama2"
        ;;
esac
