#!/usr/bin/env bash
#
# Quick SOPS + typedialog Demo
#
# Minimal script showing SOPS encryption workflow with typedialog
# No complex test framework - just shows the actual commands and results
#
# Usage:
#   bash examples/08-encryption/quick-sops-demo.sh
#

set -e

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

# Setup
DEMO_DIR="/tmp/sops-td-quick-demo"
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  SOPS + typedialog Quick Demo${NC}"
echo -e "${BLUE}========================================${NC}\n"

# Step 1: Verify tools
echo -e "${YELLOW}Step 1: Verify Tools${NC}"
echo "  Checking: sops, age-keygen, typedialog..."
sops --version | head -1 | sed 's/^/    /'
age-keygen --version 2>/dev/null | sed 's/^/    /' || echo "    age-keygen: OK"
echo -e "${GREEN}  ✓ All tools available\n${NC}"

# Step 2: Create demo directory
echo -e "${YELLOW}Step 2: Setup Demo Environment${NC}"
mkdir -p "$DEMO_DIR"
cd "$DEMO_DIR"
echo "    Demo directory: $DEMO_DIR"

# Generate Age key
echo "    Generating Age key..."
AGE_KEY_FILE="$DEMO_DIR/key.txt"
age-keygen -o "$AGE_KEY_FILE" > /dev/null 2>&1
AGE_PUBLIC_KEY=$(grep "^# public key:" "$AGE_KEY_FILE" | sed 's/# public key: //')
echo "    Age key: $(basename $AGE_KEY_FILE)"

# Create .sops.yaml
cat > ".sops.yaml" << EOF
creation_rules:
  - path_regex: .*
    age: $AGE_PUBLIC_KEY
EOF
echo "    .sops.yaml created"
echo -e "${GREEN}  ✓ Environment ready\n${NC}"

# Step 3: Test SOPS directly
echo -e "${YELLOW}Step 3: Test SOPS Encryption${NC}"
echo "    Creating plaintext YAML file..."
cat > "test-secret.yaml" << 'EOF'
secret: my-super-secret-password-123
EOF
sed 's/^/      /' "test-secret.yaml"

echo -e "\n    Encrypting with SOPS..."
export SOPS_AGE_KEY_FILE="$AGE_KEY_FILE"
sops -e -i "test-secret.yaml" > /dev/null 2>&1
echo "      Encrypted!"

echo -e "\n    Encrypted content (first 80 chars):"
head -c 80 "test-secret.yaml" | sed 's/^/      /'
echo -e "\n"

echo "    Decrypting to verify..."
PLAINTEXT=$(sops -d "test-secret.yaml" 2>/dev/null | grep "secret:" | sed 's/secret: //')
if [ "$PLAINTEXT" = "my-super-secret-password-123" ]; then
    echo "      Decrypted: $PLAINTEXT"
    echo -e "${GREEN}  ✓ SOPS encryption/decryption works\n${NC}"
else
    echo -e "${RED}  ✗ Decryption failed\n${NC}"
    echo "      Got: $PLAINTEXT"
fi

# Step 4: Test typedialog redaction (no encryption needed)
echo -e "${YELLOW}Step 4: Test typedialog Redaction${NC}"
echo "    Running: typedialog form simple-login.toml --redact"

# Extract JSON from output (skip informational lines)
OUTPUT=$(echo -e "alice\nsecretpass" | \
    typedialog form "$PROJECT_ROOT/examples/08-encryption/simple-login.toml" \
    --redact --format json 2>/dev/null | grep -A 100 "^{")

echo "    Output:"
echo "$OUTPUT" | jq '.' 2>/dev/null | sed 's/^/      /'

if echo "$OUTPUT" | jq -e '.password == "[REDACTED]"' > /dev/null 2>&1; then
    echo -e "${GREEN}  ✓ Redaction works\n${NC}"
else
    echo -e "${YELLOW}  ⚠ Redaction output: $(echo "$OUTPUT" | jq '.password' 2>/dev/null)\n${NC}"
fi

# Step 5: Test typedialog with Age backend
echo -e "${YELLOW}Step 5: Test typedialog with Age Backend${NC}"
echo "    Running: typedialog form simple-login.toml --encrypt --backend age"

OUTPUT=$(echo -e "alice\nsecretpass" | \
    typedialog form "$PROJECT_ROOT/examples/08-encryption/simple-login.toml" \
    --encrypt --backend age --key-file "$AGE_KEY_FILE" \
    --format json 2>/dev/null | grep -A 100 "^{")

echo "    Encrypted output:"
PASSWORD_CT=$(echo "$OUTPUT" | jq -r '.password' 2>/dev/null)
USERNAME=$(echo "$OUTPUT" | jq -r '.username' 2>/dev/null)
echo "      username: $USERNAME"
echo "      password: ${PASSWORD_CT:0:50}..."

if echo "$PASSWORD_CT" | grep -q "age1"; then
    echo -e "${GREEN}  ✓ Age encryption works\n${NC}"
else
    echo -e "${YELLOW}  ⚠ Output: $PASSWORD_CT\n${NC}"
fi

# Step 6: Test typedialog with SOPS backend
echo -e "${YELLOW}Step 6: Test typedialog with SOPS Backend${NC}"
echo "    Running: typedialog form simple-login.toml --encrypt --backend sops"
echo "    (Using .sops.yaml with Age backend)"

OUTPUT=$(echo -e "alice\nsecretpass" | \
    typedialog form "$PROJECT_ROOT/examples/08-encryption/simple-login.toml" \
    --encrypt --backend sops \
    --format json 2>/dev/null | grep -A 100 "^{" || true)

echo "    Encrypted output:"
PASSWORD_CT=$(echo "$OUTPUT" | jq -r '.password' 2>/dev/null)
USERNAME=$(echo "$OUTPUT" | jq -r '.username' 2>/dev/null)

if [ -n "$PASSWORD_CT" ] && [ "$PASSWORD_CT" != "null" ]; then
    echo "      username: $USERNAME"
    echo "      password: ${PASSWORD_CT:0:50}..."

    if echo "$PASSWORD_CT" | grep -q "sops:v1:"; then
        echo -e "${GREEN}  ✓ SOPS encryption works\n${NC}"
    else
        echo -e "${YELLOW}  ⚠ Password encrypted: ${PASSWORD_CT:0:30}...\n${NC}"
    fi
else
    echo -e "${YELLOW}  ⚠ SOPS test output:\n${NC}"
    while IFS= read -r line; do
        echo "      $line"
    done <<< "$OUTPUT"
    echo ""
fi

# Summary
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Demo Complete!${NC}"
echo -e "${BLUE}========================================${NC}\n"

echo "Demo directory: $DEMO_DIR"
echo "Files created:"
find "$DEMO_DIR" -maxdepth 1 -type f -printf '  - %f\n' | sort

echo -e "\n${YELLOW}Key Takeaways:${NC}"
echo "  ✓ SOPS can encrypt/decrypt YAML files"
echo "  ✓ typedialog can use SOPS backend for field encryption"
echo "  ✓ Same form works with Age, SOPS, AWS KMS, etc."
echo "  ✓ Redaction works without any encryption service"

echo -e "\n${YELLOW}Next Steps:${NC}"
echo "  1. Try with AWS KMS:"
echo "     - Create .sops.yaml with AWS KMS ARN"
echo "     - Set AWS credentials: export AWS_REGION=us-east-1"
echo "     - Run: typedialog form ... --encrypt --backend sops"
echo ""
echo "  2. Review examples:"
echo "     - Multi-backend: examples/08-encryption/multi-backend-sops.toml"
echo "     - Nickel schema: examples/08-encryption/sops-example.ncl"
echo ""
echo "  3. Read full guide:"
echo "     - examples/08-encryption/sops-demo.md"
echo "     - docs/ENCRYPTION-UNIFIED-ARCHITECTURE.md"

echo -e "\n${YELLOW}Cleanup:${NC}"
echo "  rm -rf $DEMO_DIR"

echo ""
