#!/bin/bash
#
# Docker Compose Generator - Interactive Compose File Creation
# Generates production-ready Docker Compose configurations from templates
#
# Usage: ./generate-compose.sh [options]
#

set -e

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

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"; }

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEMPLATES_DIR="$(dirname "$SCRIPT_DIR")/templates"

# Show help
show_help() {
    cat << EOF
Docker Compose Generator

Usage: $0 [OPTIONS]

Options:
    -h, --help              Show this help message
    -t, --template TYPE     Template type
    -o, --output DIR        Output directory (default: current directory)
    -n, --name NAME         Project name

Interactive Mode:
    Run without arguments for interactive prompts

Templates:
    fullstack-web-app       - Frontend + Backend + PostgreSQL + Redis
    wordpress               - WordPress + MySQL + Redis + phpMyAdmin
    dev-environment         - Development setup with hot-reload and tools
    microservices           - API Gateway + Multiple services + Message queue
    monitoring-stack        - Prometheus + Grafana + Alertmanager + Loki

Examples:
    $0 -t fullstack-web-app -n myapp
    $0 -t wordpress -o ./wordpress-site
    $0  # Interactive mode

EOF
}

# Parse arguments
TEMPLATE=""
OUTPUT_DIR="."
PROJECT_NAME=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -t|--template)
            TEMPLATE="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_DIR="$2"
            shift 2
            ;;
        -n|--name)
            PROJECT_NAME="$2"
            shift 2
            ;;
        *)
            print_error "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Interactive mode
if [[ -z "$TEMPLATE" ]]; then
    echo
    print_info "Available templates:"
    echo "  1) fullstack-web-app    - Complete web application stack"
    echo "  2) wordpress            - WordPress CMS with cache"
    echo "  3) dev-environment      - Development environment with tools"
    echo "  4) microservices        - Microservices architecture"
    echo "  5) monitoring-stack     - Complete monitoring solution"
    echo
    read -p "Select template (1-5): " template_selection

    case $template_selection in
        1) TEMPLATE="fullstack-web-app" ;;
        2) TEMPLATE="wordpress" ;;
        3) TEMPLATE="dev-environment" ;;
        4) TEMPLATE="microservices" ;;
        5) TEMPLATE="monitoring-stack" ;;
        *)
            print_error "Invalid selection"
            exit 1
            ;;
    esac
fi

# Validate template
if [[ ! -d "$TEMPLATES_DIR/$TEMPLATE" ]]; then
    print_error "Template '$TEMPLATE' not found"
    print_info "Available templates: fullstack-web-app, wordpress, dev-environment, microservices, monitoring-stack"
    exit 1
fi

# Get project name if not provided
if [[ -z "$PROJECT_NAME" ]]; then
    read -p "Enter project name: " PROJECT_NAME
fi

# Validate project name
if [[ ! "$PROJECT_NAME" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]]; then
    print_error "Invalid project name. Must be lowercase alphanumeric with hyphens"
    exit 1
fi

# Create output directory
OUTPUT_PATH="$OUTPUT_DIR/$PROJECT_NAME"
if [[ -d "$OUTPUT_PATH" ]]; then
    print_warning "Directory '$OUTPUT_PATH' already exists"
    read -p "Overwrite? (y/N): " confirm
    if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
        print_info "Aborted"
        exit 0
    fi
    rm -rf "$OUTPUT_PATH"
fi

mkdir -p "$OUTPUT_PATH"

echo
print_info "Creating Docker Compose project: $PROJECT_NAME"
print_info "Template: $TEMPLATE"
print_info "Output: $OUTPUT_PATH"
echo

# Copy template files
cp -r "$TEMPLATES_DIR/$TEMPLATE"/* "$OUTPUT_PATH/"

# Create .env file from example
if [[ -f "$OUTPUT_PATH/.env.example" ]]; then
    cp "$OUTPUT_PATH/.env.example" "$OUTPUT_PATH/.env"
    print_success "Created .env file from template"
    print_warning "⚠️  IMPORTANT: Edit .env and update passwords and secrets!"
fi

# Create README
cat > "$OUTPUT_PATH/README.md" << EOF
# $PROJECT_NAME

Docker Compose project based on $TEMPLATE template.

## Quick Start

1. Edit \`.env\` file and update passwords and configuration
2. Start services:
   \`\`\`bash
   docker compose up -d
   \`\`\`
3. View logs:
   \`\`\`bash
   docker compose logs -f
   \`\`\`

## Configuration

Edit \`compose.yaml\` to customize services.
All configuration is in the \`.env\` file.

## Management Commands

\`\`\`bash
# Start services
docker compose up -d

# Stop services
docker compose down

# View status
docker compose ps

# View logs
docker compose logs -f [service-name]

# Restart a service
docker compose restart [service-name]

# Execute command in service
docker compose exec [service-name] sh
\`\`\`

## Stopping and Cleanup

\`\`\`bash
# Stop services (keeps volumes)
docker compose down

# Stop and remove volumes
docker compose down -v

# Stop and remove images
docker compose down --rmi all
\`\`\`

## Generated

Created with Docker Compose Creator
Template: $TEMPLATE
Date: $(date +"%Y-%m-%d")
EOF

print_success "Created README.md"

# Create .gitignore
cat > "$OUTPUT_PATH/.gitignore" << EOF
# Environment files with secrets
.env
.env.local

# Logs
*.log
logs/

# OS files
.DS_Store
Thumbs.db

# IDE
.vscode/
.idea/
*.swp
*.swo

# Local data
data/
backup/
EOF

print_success "Created .gitignore"

# Create docker-compose commands helper
cat > "$OUTPUT_PATH/docker-commands.sh" << 'EOF'
#!/bin/bash
# Docker Compose Command Helper

case "$1" in
    start)
        docker compose up -d
        ;;
    stop)
        docker compose down
        ;;
    restart)
        docker compose restart
        ;;
    logs)
        docker compose logs -f "${2:-}"
        ;;
    ps)
        docker compose ps
        ;;
    exec)
        docker compose exec "${2:-app}" sh
        ;;
    clean)
        docker compose down -v --remove-orphans
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|logs|ps|exec|clean}"
        exit 1
        ;;
esac
EOF

chmod +x "$OUTPUT_PATH/docker-commands.sh"
print_success "Created docker-commands.sh helper script"

# Template-specific instructions
echo
print_success "Docker Compose project created successfully!"
echo
print_info "Next steps:"
echo "  1. cd $OUTPUT_PATH"
echo "  2. Edit .env file (IMPORTANT: Change all passwords!)"
echo "  3. Review and customize compose.yaml"
echo "  4. docker compose config  # Validate configuration"
echo "  5. docker compose up -d   # Start services"
echo

case $TEMPLATE in
    fullstack-web-app)
        echo "📝 Template-specific notes:"
        echo "  • Configure your application in the backend/ directory"
        echo "  • Place frontend build in frontend/dist/"
        echo "  • Update nginx/nginx.conf for your domain"
        ;;
    wordpress)
        echo "📝 Template-specific notes:"
        echo "  • After starting, visit http://localhost to complete WordPress setup"
        echo "  • phpMyAdmin available at http://localhost:8080"
        echo "  • To enable phpMyAdmin: docker compose --profile admin up -d"
        ;;
    dev-environment)
        echo "📝 Template-specific notes:"
        echo "  • Mailhog UI: http://localhost:8025"
        echo "  • Adminer (DB): http://localhost:8080"
        echo "  • Redis Commander: http://localhost:8081"
        echo "  • All services have ports exposed for external tools"
        ;;
    microservices)
        echo "📝 Template-specific notes:"
        echo "  • Kong Admin API: http://localhost:8001"
        echo "  • RabbitMQ Management: http://localhost:15672"
        echo "  • Consul UI: http://localhost:8500"
        echo "  • Configure Kong routes via Admin API"
        ;;
    monitoring-stack)
        echo "📝 Template-specific notes:"
        echo "  • Prometheus: http://localhost:9090"
        echo "  • Grafana: http://localhost:3000 (admin/password from .env)"
        echo "  • Alertmanager: http://localhost:9093"
        echo "  • Configure alerts in prometheus/alerts/"
        ;;
esac

echo
print_info "Validate configuration:"
echo "  $SCRIPT_DIR/validate-compose.sh $OUTPUT_PATH"
echo
