#!/bin/bash

set -e

echo "╔════════════════════════════════════════════════════════════════════════╗"
echo "║               DEPLOYING POIMEN ORCHESTRATOR TO KUBERNETES              ║"
echo "╚════════════════════════════════════════════════════════════════════════╝"
echo ""

# Check if kubectl is available
if ! command -v kubectl &> /dev/null; then
    echo "❌ kubectl not found. Please install kubectl."
    exit 1
fi

# Check if temporal namespace exists
if ! kubectl get namespace temporal &> /dev/null; then
    echo "❌ Temporal namespace not found. Please deploy Temporal first."
    exit 1
fi

echo "✅ Temporal namespace found"
echo ""

# Get API key from user
echo "Step 1: Set up secrets"
echo ""
read -sp "Enter ANTHROPIC_API_KEY: " API_KEY
echo ""

# Update secret with actual API key
kubectl create secret generic poimen-secrets \
  --namespace poimen \
  --from-literal=ANTHROPIC_API_KEY="$API_KEY" \
  --dry-run=client -o yaml | kubectl apply -f -

echo "✅ Secrets configured"
echo ""

# Apply ConfigMap
echo "Step 2: Apply ConfigMap"
kubectl apply -f k8s/configmap.yaml
echo "✅ ConfigMap deployed"
echo ""

# Apply Worker Deployment
echo "Step 3: Deploy Worker"
kubectl apply -f k8s/worker-deployment.yaml
echo "✅ Worker deployment created"
echo ""

# Wait for worker to start
echo "Waiting for worker to be ready..."
kubectl wait --for=condition=available --timeout=120s \
  -n poimen deployment/poimen-worker 2>/dev/null || true
echo ""

# Check worker status
echo "Worker Status:"
kubectl get pods -n poimen -l app=poimen-worker
echo ""

# Submit orchestrator job
echo "Step 4: Submit Orchestrator Workflow"
kubectl apply -f k8s/orchestrator-job.yaml
echo "✅ Orchestrator job submitted"
echo ""

# Monitor job
echo "Monitoring orchestrator job..."
kubectl logs -n poimen -f job/poimen-orchestrator 2>/dev/null || true

echo ""
echo "════════════════════════════════════════════════════════════════════════"
echo "DEPLOYMENT COMPLETE"
echo "════════════════════════════════════════════════════════════════════════"
echo ""
echo "Monitor workflow:"
echo "  temporal workflow list --address temporal-frontend.temporal:7233 --namespace poimen-harness"
echo ""
echo "View worker logs:"
echo "  kubectl logs -n poimen -l app=poimen-worker -f"
echo ""
echo "View orchestrator job logs:"
echo "  kubectl logs -n poimen job/poimen-orchestrator -f"
echo ""
echo "Access Temporal Web UI:"
echo "  kubectl port-forward -n temporal svc/temporal-web 8080:8080"
echo "  Then open: http://localhost:8080"
echo ""
