#!/bin/bash
# Enhanced deployment script with notifications and logging

set -e

ENVIRONMENT=$1
STRATEGY=${2:-blue-green}
VERSION=${3:-latest}

if [ -z "$ENVIRONMENT" ]; then
    echo "Usage: $0 <environment> [strategy] [version]"
    exit 1
fi

DEPLOYMENT_ID="${ENVIRONMENT}-$(date +%Y%m%d%H%M%S)"
LOG_FILE="../../logs/deployments/${DEPLOYMENT_ID}.log"

mkdir -p "$(dirname "$LOG_FILE")"

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "Starting deployment: $ENVIRONMENT"
log "Strategy: $STRATEGY"
log "Version: $VERSION"

# Load environment config
ENV_CONFIG=$(python3 << EOF
import yaml
import json
import sys

with open('../../config/environments.yaml', 'r') as f:
    config = yaml.safe_load(f)
    for env in config.get('environments', []):
        if env.get('name') == '$ENVIRONMENT':
            print(json.dumps(env))
            sys.exit(0)
sys.exit(1)
EOF
)

if [ $? -ne 0 ]; then
    log "ERROR: Environment $ENVIRONMENT not found"
    exit 1
fi

PROVIDER=$(echo "$ENV_CONFIG" | python3 -c "import sys, json; print(json.load(sys.stdin).get('provider', 'unknown'))")

log "Provider: $PROVIDER"

# Deploy based on strategy
case $STRATEGY in
    blue-green)
        log "Executing blue-green deployment..."
        ../../orchestration/strategies/blue-green.sh "$ENVIRONMENT" "$VERSION" >> "$LOG_FILE" 2>&1
        ;;
    canary)
        PERCENTAGE=${4:-10}
        log "Executing canary deployment ($PERCENTAGE%)..."
        ../../orchestration/strategies/canary.sh "$ENVIRONMENT" "$VERSION" "$PERCENTAGE" >> "$LOG_FILE" 2>&1
        ;;
    rolling)
        log "Executing rolling deployment..."
        # Rolling deployment logic here
        ;;
    *)
        log "ERROR: Unknown strategy $STRATEGY"
        exit 1
        ;;
esac

if [ $? -eq 0 ]; then
    log "✅ Deployment completed successfully"
    
    # Send notification (if configured)
    if [ -n "$SLACK_WEBHOOK_URL" ]; then
        curl -X POST "$SLACK_WEBHOOK_URL" \
            -H 'Content-Type: application/json' \
            -d "{\"text\":\"✅ Deployment completed: $ENVIRONMENT ($VERSION)\"}" || true
    fi
    
    exit 0
else
    log "❌ Deployment failed"
    
    # Send failure notification
    if [ -n "$SLACK_WEBHOOK_URL" ]; then
        curl -X POST "$SLACK_WEBHOOK_URL" \
            -H 'Content-Type: application/json' \
            -d "{\"text\":\"❌ Deployment failed: $ENVIRONMENT ($VERSION)\"}" || true
    fi
    
    exit 1
fi

