#!/bin/bash

# Docker Management Script for TAF TaxCore Service
# Provides easy commands for managing the Dockerized TaxCore service

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

# Function to print colored messages
print_info() {
    echo -e "${BLUE}ℹ ${NC}$1"
}

print_success() {
    echo -e "${GREEN}✓ ${NC}$1"
}

print_warning() {
    echo -e "${YELLOW}⚠ ${NC}$1"
}

print_error() {
    echo -e "${RED}✗ ${NC}$1"
}

# Function to check if Docker is installed
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker is not installed!"
        echo "Please install Docker: https://docs.docker.com/get-docker/"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose is not installed!"
        echo "Please install Docker Compose: https://docs.docker.com/compose/install/"
        exit 1
    fi
    
    print_success "Docker and Docker Compose are installed"
}

# Function to check certificate
check_certificate() {
    print_info "Checking for TaxCore certificate..."
    
    if [ -d "FRCS_Certs_Install" ]; then
        CERT_COUNT=$(find FRCS_Certs_Install -name "*.pfx" 2>/dev/null | wc -l)
        if [ "$CERT_COUNT" -gt 0 ]; then
            print_success "Found $CERT_COUNT certificate(s) in FRCS_Certs_Install/"
            find FRCS_Certs_Install -name "*.pfx" -exec ls -lh {} \;
        else
            print_warning "No .pfx certificates found in FRCS_Certs_Install/"
            print_info "Place your certificate file in FRCS_Certs_Install/ directory"
        fi
    else
        print_warning "FRCS_Certs_Install directory not found"
        print_info "Creating directory..."
        mkdir -p FRCS_Certs_Install
        print_success "Created FRCS_Certs_Install directory"
        print_info "Please place your certificate file in this directory"
    fi
}

# Function to check .env file
check_env() {
    print_info "Checking environment configuration..."
    
    if [ -f ".env" ]; then
        print_success ".env file exists"
    else
        print_warning ".env file not found"
        if [ -f ".env.docker" ]; then
            read -p "Copy .env.docker to .env? (y/n) " -n 1 -r
            echo
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                cp .env.docker .env
                print_success "Created .env from .env.docker"
                print_info "Please edit .env with your configuration"
            fi
        else
            print_info "Please create .env file with your configuration"
        fi
    fi
}

# Function to build services
build_services() {
    print_info "Building Docker services..."
    
    if [ "$1" == "taxcore" ]; then
        docker-compose build taxcore-service
        print_success "TaxCore service built successfully"
    else
        docker-compose build
        print_success "All services built successfully"
    fi
}

# Function to start services
start_services() {
    print_info "Starting Docker services..."
    
    if [ "$1" == "taxcore" ]; then
        docker-compose up -d taxcore-service
        print_success "TaxCore service started"
    else
        docker-compose up -d
        print_success "All services started"
    fi
    
    # Wait a moment for services to initialize
    sleep 3
    
    # Show status
    docker-compose ps
}

# Function to stop services
stop_services() {
    print_info "Stopping Docker services..."
    
    if [ "$1" == "taxcore" ]; then
        docker-compose stop taxcore-service
        print_success "TaxCore service stopped"
    else
        docker-compose down
        print_success "All services stopped"
    fi
}

# Function to view logs
view_logs() {
    print_info "Viewing logs..."
    
    if [ "$1" == "taxcore" ]; then
        docker-compose logs -f taxcore-service
    else
        docker-compose logs -f
    fi
}

# Function to test TaxCore service
test_service() {
    print_info "Testing TaxCore service..."
    
    # Check if container is running
    if ! docker-compose ps | grep -q "taxcore-service.*Up"; then
        print_error "TaxCore service is not running"
        print_info "Start the service with: $0 start taxcore"
        exit 1
    fi
    
    # Test health endpoint
    print_info "Testing health endpoint..."
    if curl -f -s http://localhost:3001/health > /dev/null; then
        print_success "Health check passed"
        HEALTH=$(curl -s http://localhost:3001/health)
        echo "Response: $HEALTH"
    else
        print_error "Health check failed"
        print_info "Check logs with: $0 logs taxcore"
        exit 1
    fi
    
    # Test from PHP container
    print_info "Testing from PHP container..."
    if docker-compose exec -T php-apache curl -f -s http://taxcore-service:3001/health > /dev/null; then
        print_success "PHP can communicate with TaxCore service"
    else
        print_error "PHP cannot communicate with TaxCore service"
        print_info "Check network configuration"
    fi
}

# Function to restart service
restart_service() {
    print_info "Restarting service..."
    
    if [ "$1" == "taxcore" ]; then
        docker-compose restart taxcore-service
        print_success "TaxCore service restarted"
    else
        docker-compose restart
        print_success "All services restarted"
    fi
}

# Function to show service status
show_status() {
    print_info "Service Status:"
    docker-compose ps
    
    echo ""
    print_info "Resource Usage:"
    docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}" \
        $(docker-compose ps -q)
}

# Function to execute command in container
exec_command() {
    print_info "Executing command in TaxCore container..."
    docker-compose exec taxcore-service "$@"
}

# Function to show help
show_help() {
    cat << EOF
${GREEN}TAF Docker Management Script${NC}

${BLUE}Usage:${NC}
  $0 <command> [options]

${BLUE}Commands:${NC}
  ${GREEN}check${NC}           - Check prerequisites (Docker, certificates, .env)
  ${GREEN}build${NC} [service] - Build Docker images (all or 'taxcore')
  ${GREEN}start${NC} [service] - Start services (all or 'taxcore')
  ${GREEN}stop${NC} [service]  - Stop services (all or 'taxcore')
  ${GREEN}restart${NC} [svc]   - Restart services (all or 'taxcore')
  ${GREEN}logs${NC} [service]  - View logs (all or 'taxcore')
  ${GREEN}test${NC}            - Test TaxCore service connection
  ${GREEN}status${NC}          - Show service status and resource usage
  ${GREEN}exec${NC} <command>  - Execute command in TaxCore container
  ${GREEN}clean${NC}           - Stop and remove all containers
  ${GREEN}help${NC}            - Show this help message

${BLUE}Examples:${NC}
  $0 check              # Check prerequisites
  $0 build taxcore      # Build only TaxCore service
  $0 start              # Start all services
  $0 start taxcore      # Start only TaxCore service
  $0 logs taxcore       # View TaxCore service logs
  $0 test               # Test TaxCore service
  $0 exec sh            # Open shell in TaxCore container
  $0 restart taxcore    # Restart TaxCore service
  $0 stop               # Stop all services
  $0 clean              # Remove all containers

${BLUE}Quick Start:${NC}
  1. $0 check           # Verify setup
  2. $0 build           # Build all services
  3. $0 start           # Start all services
  4. $0 test            # Test TaxCore service
  5. $0 logs taxcore    # View logs

${BLUE}Configuration:${NC}
  - Edit .env file for environment variables
  - Place certificates in FRCS_Certs_Install/
  - See docker/taxcore-service/README.md for details

EOF
}

# Main script logic
case "${1:-}" in
    check)
        check_docker
        check_certificate
        check_env
        ;;
    build)
        check_docker
        build_services "$2"
        ;;
    start)
        check_docker
        start_services "$2"
        ;;
    stop)
        stop_services "$2"
        ;;
    restart)
        restart_service "$2"
        ;;
    logs)
        view_logs "$2"
        ;;
    test)
        test_service
        ;;
    status)
        show_status
        ;;
    exec)
        shift
        exec_command "$@"
        ;;
    clean)
        print_warning "This will stop and remove all containers"
        read -p "Are you sure? (y/n) " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            docker-compose down
            print_success "All containers removed"
        fi
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        print_error "Unknown command: ${1:-}"
        echo ""
        show_help
        exit 1
        ;;
esac

exit 0
