#!/bin/bash

# Production Deployment Script for MicroK8s
# This script helps deploy Bakery IA to a MicroK8s cluster

set -e

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

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Bakery IA - Production Deployment${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# Configuration
NAMESPACE="bakery-ia"
KUSTOMIZE_PATH="infrastructure/environments/prod/k8s-manifests"

# Check if kubectl is available
if ! command -v kubectl &> /dev/null; then
    echo -e "${RED}Error: kubectl not found. Please install kubectl or setup microk8s alias.${NC}"
    exit 1
fi

# Function to check if cluster is accessible
check_cluster() {
    echo -e "${YELLOW}Checking cluster connectivity...${NC}"
    if ! kubectl cluster-info &> /dev/null; then
        echo -e "${RED}Error: Cannot connect to Kubernetes cluster.${NC}"
        echo "Please ensure your kubeconfig is set correctly."
        exit 1
    fi
    echo -e "${GREEN}✓ Cluster connection successful${NC}"
    echo ""
}

# Function to check required addons
check_addons() {
    echo -e "${YELLOW}Checking required MicroK8s addons...${NC}"

    # Check if this is MicroK8s
    if command -v microk8s &> /dev/null; then
        REQUIRED_ADDONS=("dns" "hostpath-storage" "ingress" "cert-manager" "metrics-server")

        for addon in "${REQUIRED_ADDONS[@]}"; do
            if microk8s status | grep -q "$addon: enabled"; then
                echo -e "${GREEN}✓ $addon enabled${NC}"
            else
                echo -e "${RED}✗ $addon not enabled${NC}"
                echo -e "${YELLOW}Enable with: microk8s enable $addon${NC}"
                exit 1
            fi
        done
    else
        echo -e "${YELLOW}Not running on MicroK8s. Skipping addon check.${NC}"
    fi
    echo ""
}

# Function to create namespace
create_namespace() {
    echo -e "${YELLOW}Creating namespace...${NC}"
    if kubectl get namespace $NAMESPACE &> /dev/null; then
        echo -e "${GREEN}✓ Namespace $NAMESPACE already exists${NC}"
    else
        kubectl create namespace $NAMESPACE
        echo -e "${GREEN}✓ Namespace $NAMESPACE created${NC}"
    fi
    echo ""
}

# Function to apply secrets
apply_secrets() {
    echo -e "${YELLOW}Applying secrets...${NC}"
    echo -e "${RED}WARNING: Ensure production secrets are updated before deployment!${NC}"
    read -p "Have you updated production secrets? (yes/no): " confirm

    if [ "$confirm" != "yes" ]; then
        echo -e "${RED}Deployment cancelled. Please update secrets first.${NC}"
        exit 1
    fi

    kubectl apply -f infrastructure/kubernetes/base/secrets.yaml
    kubectl apply -f infrastructure/kubernetes/base/secrets/postgres-tls-secret.yaml
    kubectl apply -f infrastructure/kubernetes/base/secrets/redis-tls-secret.yaml
    kubectl apply -f infrastructure/kubernetes/base/secrets/demo-internal-api-key-secret.yaml
    echo -e "${GREEN}✓ Secrets applied${NC}"
    echo ""
}

# Function to apply kustomization
deploy_application() {
    echo -e "${YELLOW}Deploying application...${NC}"
    kubectl apply -k $KUSTOMIZE_PATH
    echo -e "${GREEN}✓ Application deployed${NC}"
    echo ""
}

# Function to wait for deployments
wait_for_deployments() {
    echo -e "${YELLOW}Waiting for deployments to be ready...${NC}"
    echo "This may take several minutes..."

    # Wait for all deployments
    kubectl wait --for=condition=available --timeout=600s \
        deployment --all -n $NAMESPACE

    echo -e "${GREEN}✓ All deployments are ready${NC}"
    echo ""
}

# Function to check deployment status
check_status() {
    echo -e "${YELLOW}Deployment Status:${NC}"
    echo ""

    echo "Pods:"
    kubectl get pods -n $NAMESPACE
    echo ""

    echo "Services:"
    kubectl get svc -n $NAMESPACE
    echo ""

    echo "Ingress:"
    kubectl get ingress -n $NAMESPACE
    echo ""

    echo "Persistent Volume Claims:"
    kubectl get pvc -n $NAMESPACE
    echo ""

    echo "Certificates:"
    kubectl get certificate -n $NAMESPACE
    echo ""
}

# Function to show access information
show_access_info() {
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}Deployment Complete!${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo "Access your application at:"

    # Get ingress hosts
    HOSTS=$(kubectl get ingress bakery-ingress-prod -n $NAMESPACE -o jsonpath='{.spec.rules[*].host}' 2>/dev/null || echo "")

    if [ -n "$HOSTS" ]; then
        for host in $HOSTS; do
            echo "  https://$host"
        done
    else
        echo "  Configure your domain in prod-ingress.yaml"
    fi

    echo ""
    echo "Useful commands:"
    echo "  View logs:    kubectl logs -f deployment/gateway -n $NAMESPACE"
    echo "  Check pods:   kubectl get pods -n $NAMESPACE"
    echo "  Check events: kubectl get events -n $NAMESPACE --sort-by='.lastTimestamp'"
    echo "  Scale:        kubectl scale deployment/gateway --replicas=5 -n $NAMESPACE"
    echo ""
}

# Main deployment flow
main() {
    check_cluster
    check_addons
    create_namespace
    apply_secrets
    deploy_application

    echo -e "${YELLOW}Do you want to wait for deployments to be ready? (yes/no):${NC}"
    read -p "> " wait_confirm

    if [ "$wait_confirm" = "yes" ]; then
        wait_for_deployments
    fi

    check_status
    show_access_info
}

# Run main function
main
