#!/usr/bin/env bash
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

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

usage() {
    echo "Usage: $0 [ENVIRONMENT] [SECRET_NAME]"
    echo ""
    echo "Update Kubernetes secrets from YAML files"
    echo ""
    echo "Arguments:"
    echo "  ENVIRONMENT   Target environment: dev or prod (default: dev)"
    echo "  SECRET_NAME   Specific secret to update (optional, updates all if not specified)"
    echo ""
    echo "Available secrets:"
    echo "  ai-secrets        - AI backend API keys"
    echo "  postgres-secret   - PostgreSQL password"
    echo "  minio-secret      - MinIO credentials"
    echo "  ingestor-secrets  - Exchange API keys"
    echo ""
    echo "Examples:"
    echo "  $0                          # Update all dev secrets"
    echo "  $0 dev                      # Update all dev secrets"
    echo "  $0 dev ai-secrets           # Update only ai-secrets in dev"
    echo "  $0 prod                     # Update all prod secrets"
    echo "  $0 prod minio-secret        # Update only minio-secret in prod"
    exit 1
}

# Parse arguments
ENV="${1:-dev}"
SECRET_NAME="${2:-}"

if [[ "$ENV" != "dev" && "$ENV" != "prod" ]]; then
    echo -e "${RED}Error: Environment must be 'dev' or 'prod'${NC}"
    usage
fi

SECRETS_DIR="$ROOT_DIR/deploy/k8s/$ENV/secrets"

if [ ! -d "$SECRETS_DIR" ]; then
    echo -e "${RED}Error: Secrets directory not found: $SECRETS_DIR${NC}"
    exit 1
fi

# Get kubectl context
if [[ "$ENV" == "prod" ]]; then
    CONTEXT=$(kubectl config current-context)
    echo -e "${YELLOW}⚠️  WARNING: Updating PRODUCTION secrets!${NC}"
    echo -e "${YELLOW}Current kubectl context: $CONTEXT${NC}"
    read -p "Are you sure you want to continue? (yes/no): " confirm
    if [[ "$confirm" != "yes" ]]; then
        echo "Aborted."
        exit 0
    fi
fi

apply_secret() {
    local secret_file="$1"
    local secret_basename=$(basename "$secret_file" .yaml)

    if [ ! -f "$secret_file" ]; then
        echo -e "${RED}✗ Secret file not found: $secret_file${NC}"
        echo -e "${YELLOW}  Copy from ${secret_basename}.yaml.example and fill in values${NC}"
        return 1
    fi

    echo -e "${GREEN}→${NC} Applying $secret_basename..."
    kubectl apply -f "$secret_file"
    echo -e "${GREEN}✓${NC} $secret_basename updated"
}

# Update specific secret or all secrets
if [ -n "$SECRET_NAME" ]; then
    # Update single secret
    SECRET_FILE="$SECRETS_DIR/$SECRET_NAME.yaml"
    apply_secret "$SECRET_FILE"
else
    # Update all secrets
    echo -e "${GREEN}Updating all $ENV secrets...${NC}"
    echo ""

    SECRETS=(
        "ai-secrets"
        "postgres-secret"
        "minio-secret"
        "ingestor-secrets"
        "flink-secrets"
    )

    FAILED=0
    for secret in "${SECRETS[@]}"; do
        SECRET_FILE="$SECRETS_DIR/$secret.yaml"
        if ! apply_secret "$SECRET_FILE"; then
            FAILED=$((FAILED + 1))
        fi
    done

    echo ""
    if [ $FAILED -gt 0 ]; then
        echo -e "${YELLOW}⚠️  $FAILED secret(s) failed to apply${NC}"
        echo -e "${YELLOW}Create missing secret files by copying from .example templates:${NC}"
        echo -e "${YELLOW}  cd $SECRETS_DIR${NC}"
        echo -e "${YELLOW}  cp SECRET_NAME.yaml.example SECRET_NAME.yaml${NC}"
        echo -e "${YELLOW}  # Edit SECRET_NAME.yaml with actual values${NC}"
        exit 1
    else
        echo -e "${GREEN}✓ All secrets updated successfully${NC}"
    fi
fi
