#!/bin/bash

# PDF Module Management Script
# This script provides easy commands to manage the PDF processing module

set -e

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

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BACKEND_DIR="$(dirname "$SCRIPT_DIR")"

echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE}   PDF Module Management Script${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""

# Function to show usage
show_usage() {
    echo "Usage: ./pdf-module.sh [command]"
    echo ""
    echo "Commands:"
    echo "  test           Run PDF module tests"
    echo "  init           Initialize and process all PDFs"
    echo "  start          Start the PDF worker"
    echo "  stop           Stop the PDF worker"
    echo "  status         Show worker and queue status"
    echo "  stats          Show processing statistics"
    echo "  clean          Clean old jobs from queue"
    echo "  retry          Retry failed jobs"
    echo "  help           Show this help message"
    echo ""
}

# Function to run tests
run_tests() {
    echo -e "${GREEN}🧪 Running PDF Module Tests...${NC}"
    echo ""
    cd "$BACKEND_DIR"
    npx tsx src/modules/pdf/test-pdf-module.ts
}

# Function to initialize module
init_module() {
    echo -e "${GREEN}🚀 Initializing PDF Module...${NC}"
    echo ""
    cd "$BACKEND_DIR"
    npx tsx src/modules/pdf/pdf.init.ts
}

# Function to start worker
start_worker() {
    echo -e "${GREEN}▶️  Starting PDF Worker...${NC}"
    echo ""
    echo "The worker needs to be started within the Node.js application."
    echo "Use 'npm run dev' to start the backend server with the worker."
    echo ""
    echo "Or add this to your server.ts:"
    echo "  const worker = container.resolve(PDFProcessorWorker);"
    echo "  await worker.start();"
}

# Function to show status
show_status() {
    echo -e "${GREEN}📊 Worker and Queue Status${NC}"
    echo ""
    echo "This command requires the worker to be running."
    echo "Please implement a status endpoint in your API or use Redis CLI:"
    echo ""
    echo "  redis-cli"
    echo "  > KEYS bull:pdf-process:*"
    echo "  > HGETALL bull:pdf-process:1"
}

# Function to show statistics
show_stats() {
    echo -e "${GREEN}📈 Processing Statistics${NC}"
    echo ""
    echo "Query database for statistics:"
    echo ""
    cd "$BACKEND_DIR"
    npx tsx -e "
    import { PrismaClient } from '@prisma/client';
    const prisma = new PrismaClient();

    async function stats() {
      const total = await prisma.pDF.count();
      const processed = await prisma.pDF.count({ where: { processed: true } });
      const pending = total - processed;

      console.log(\`Total PDFs: \${total}\`);
      console.log(\`Processed: \${processed}\`);
      console.log(\`Pending: \${pending}\`);
      console.log(\`Completion: \${((processed/total)*100).toFixed(1)}%\`);

      await prisma.\$disconnect();
    }

    stats().catch(console.error);
    "
}

# Function to clean old jobs
clean_jobs() {
    echo -e "${YELLOW}🧹 Cleaning old jobs...${NC}"
    echo ""
    echo "This command requires the worker to be running."
    echo "Use the Redis CLI to clean old jobs:"
    echo ""
    echo "  redis-cli --scan --pattern 'bull:pdf-process:*' | xargs redis-cli DEL"
}

# Function to retry failed jobs
retry_failed() {
    echo -e "${YELLOW}🔄 Retrying failed jobs...${NC}"
    echo ""
    echo "This command requires the worker to be running."
    echo "Implement a retry endpoint or use the worker directly:"
    echo ""
    echo "  await worker.retryFailedJobs();"
}

# Main script logic
case "${1:-help}" in
    test)
        run_tests
        ;;
    init)
        init_module
        ;;
    start)
        start_worker
        ;;
    stop)
        echo -e "${YELLOW}⏹️  Stopping PDF Worker...${NC}"
        echo ""
        echo "The worker stops when the Node.js process terminates."
        echo "Use Ctrl+C or kill the process to stop."
        ;;
    status)
        show_status
        ;;
    stats)
        show_stats
        ;;
    clean)
        clean_jobs
        ;;
    retry)
        retry_failed
        ;;
    help|--help|-h)
        show_usage
        ;;
    *)
        echo -e "${RED}❌ Unknown command: $1${NC}"
        echo ""
        show_usage
        exit 1
        ;;
esac

echo ""
echo -e "${BLUE}======================================${NC}"
echo -e "${GREEN}✅ Done!${NC}"
echo -e "${BLUE}======================================${NC}"
