#!/bin/bash

# Gemini FAQ App Development Helper Script
# This script provides easy commands for development workflow

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

print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

show_help() {
    echo "Gemini FAQ App Development Helper"
    echo "================================="
    echo ""
    echo "Usage: ./dev.sh [command]"
    echo ""
    echo "Commands:"
    echo "  setup     - Run complete application setup"
    echo "  start     - Start all application services"
    echo "  status    - Check status of all services"
    echo "  test      - Run application tests"
    echo "  clean     - Clean up development environment"
    echo "  logs      - Show application logs"
    echo "  help      - Show this help message"
    echo ""
    echo "Examples:"
    echo "  ./dev.sh setup    # Initial setup"
    echo "  ./dev.sh start    # Start development servers"
    echo "  ./dev.sh status   # Check if services are running"
    echo ""
}

check_setup() {
    if [ ! -f .env ]; then
        print_error "Application not set up. Please run: ./dev.sh setup"
        return 1
    fi
    return 0
}

run_setup() {
    print_status "Running application setup..."
    ./setup.sh
}

start_services() {
    if ! check_setup; then
        exit 1
    fi
    print_status "Starting application services..."
    ./start.sh
}

check_status() {
    echo "Service Status Check"
    echo "==================="
    echo ""
    
    # Check DDEV
    if ddev status >/dev/null 2>&1; then
        print_success "✓ DDEV is running"
    else
        print_error "✗ DDEV is not running"
    fi
    
    # Check Python service
    if curl -s http://127.0.0.1:5002/health >/dev/null 2>&1; then
        print_success "✓ Python RAG service is running (port 5002)"
    else
        print_warning "⚠ Python RAG service not responding (port 5002)"
    fi
    
    # Check Laravel API
    if check_setup; then
        DDEV_URL=$(ddev describe 2>/dev/null | grep "https://" | head -1 | awk '{print $2}' || echo "")
        if [ -n "$DDEV_URL" ] && curl -s "${DDEV_URL}/api/content/status" >/dev/null 2>&1; then
            print_success "✓ Laravel API is responding"
            echo "  URL: ${DDEV_URL}"
        else
            print_warning "⚠ Laravel API not responding"
        fi
    fi
    
    # Check for running processes
    if pgrep -f "npm run dev" >/dev/null; then
        print_success "✓ Vite development server is running"
    else
        print_warning "⚠ Vite development server not running"
    fi
    
    if pgrep -f "python3 app.py" >/dev/null; then
        print_success "✓ Python RAG service process is running"
    else
        print_warning "⚠ Python RAG service process not found"
    fi
}

run_tests() {
    if ! check_setup; then
        exit 1
    fi
    
    print_status "Running application tests..."
    
    # Test API endpoints
    DDEV_URL=$(ddev describe 2>/dev/null | grep "https://" | head -1 | awk '{print $2}' || echo "")
    
    if [ -n "$DDEV_URL" ]; then
        print_status "Testing Laravel API endpoints..."
        
        # Test status endpoint
        if curl -s "${DDEV_URL}/api/content/status" | grep -q "ok\|success\|healthy" 2>/dev/null; then
            print_success "✓ Status endpoint working"
        else
            print_warning "⚠ Status endpoint test failed"
        fi
    fi
    
    # Test Python service
    if curl -s http://127.0.0.1:5002/health >/dev/null 2>&1; then
        print_success "✓ Python service health check passed"
    else
        print_warning "⚠ Python service health check failed"
    fi
    
    # Test Gemini API if service is running
    if curl -s http://127.0.0.1:5002/test-gemini >/dev/null 2>&1; then
        print_success "✓ Gemini API connection working"
    else
        print_warning "⚠ Gemini API connection test failed"
    fi
}

clean_environment() {
    print_status "Cleaning development environment..."
    
    # Stop services
    print_status "Stopping services..."
    pkill -f "npm run dev" 2>/dev/null || true
    pkill -f "python3 app.py" 2>/dev/null || true
    
    # Clear Laravel caches
    if check_setup; then
        print_status "Clearing Laravel caches..."
        ddev artisan cache:clear 2>/dev/null || true
        ddev artisan config:clear 2>/dev/null || true
        ddev artisan route:clear 2>/dev/null || true
        ddev artisan view:clear 2>/dev/null || true
    fi
    
    # Clear Node modules cache
    if [ -d node_modules ]; then
        print_status "Clearing Node.js build cache..."
        rm -rf public/build/* 2>/dev/null || true
    fi
    
    print_success "Environment cleaned!"
}

show_logs() {
    if ! check_setup; then
        exit 1
    fi
    
    echo "Application Logs"
    echo "==============="
    echo ""
    
    print_status "Laravel logs (last 20 lines):"
    if [ -f storage/logs/laravel.log ]; then
        tail -20 storage/logs/laravel.log
    else
        print_warning "No Laravel logs found"
    fi
    
    echo ""
    print_status "DDEV logs (last 10 lines):"
    ddev logs | tail -10 2>/dev/null || print_warning "Could not fetch DDEV logs"
}

# Main script logic
case "${1}" in
    setup)
        run_setup
        ;;
    start)
        start_services
        ;;
    status)
        check_status
        ;;
    test)
        run_tests
        ;;
    clean)
        clean_environment
        ;;
    logs)
        show_logs
        ;;
    help|--help|-h)
        show_help
        ;;
    "")
        show_help
        ;;
    *)
        print_error "Unknown command: $1"
        echo ""
        show_help
        exit 1
        ;;
esac
