#!/bin/bash
# Sync credentials to running Investibook backend pod
# This script updates clinic_credentials.json on the PVC

set -e

NAMESPACE="investibook"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "=========================================="
echo "Sync Credentials to Investibook Pod"
echo "=========================================="
echo ""

# Get backend pod name (only Running pods)
echo "Finding Running backend pod..."
POD_NAME=$(kubectl get pods -n $NAMESPACE -l app=backend --field-selector=status.phase=Running -o jsonpath='{.items[0].metadata.name}' 2>/dev/null)

if [ -z "$POD_NAME" ]; then
    echo "Error: No Running backend pod found in namespace $NAMESPACE"
    echo "   Make sure the backend deployment is running"
    exit 1
fi

echo "Found Running pod: $POD_NAME"
echo ""

# Sync clinic_credentials.json
echo "Syncing clinic_credentials.json to PVC..."
CLINIC_CREDS_PATH="$SCRIPT_DIR/../backend/data/config/clinic_credentials.json"

if [ ! -f "$CLINIC_CREDS_PATH" ]; then
    echo "Error: Local clinic_credentials.json not found at:"
    echo "   $CLINIC_CREDS_PATH"
    exit 1
fi

echo "   Source: $CLINIC_CREDS_PATH"
echo "   Target: $POD_NAME:/data/config/clinic_credentials.json"

# Ensure the config directory exists on the pod
kubectl exec -n $NAMESPACE $POD_NAME -- mkdir -p /data/config
kubectl cp "$CLINIC_CREDS_PATH" "$NAMESPACE/$POD_NAME:/data/config/clinic_credentials.json"

if [ $? -eq 0 ]; then
    echo "   clinic_credentials.json synced successfully"
    echo "   Credentials are stored on PVC -- persists across pod restarts"
    echo "   They will be picked up automatically on the next chat session"
else
    echo "   Failed to sync clinic_credentials.json"
    exit 1
fi

echo ""
echo "=========================================="
echo "All credentials synced successfully!"
echo "=========================================="
echo ""
echo "Summary:"
echo "   Pod: $POD_NAME"
echo "   Namespace: $NAMESPACE"
echo "   Files synced:"
echo "     1. /data/config/clinic_credentials.json"
echo ""
