# KMS (Key Management Service) Recipes
# ======================================
# Encryption, decryption, key management, and backend operations

# ============================================================================
# Encryption Operations
# ============================================================================

# Encrypt file with RustyVault (fastest default backend)
@kms-encrypt FILE:
    #!/usr/bin/env bash
    echo "🔒 Encrypting {{FILE}} with RustyVault..."
    provisioning kms encrypt {{FILE}} --backend rustyvault
    echo "✅ File encrypted: {{FILE}}.enc"

@kms-encrypt-backend FILE BACKEND:
    #!/usr/bin/env bash
    echo "🔒 Encrypting {{FILE}} with {{BACKEND}}..."
    provisioning kms encrypt {{FILE}} --backend {{BACKEND}}
    echo "✅ File encrypted"

@kms-decrypt FILE:
    echo "🔓 Decrypting {{FILE}}..."
    provisioning kms decrypt {{FILE}}
    echo "✅ File decrypted"

@kms-encrypt-string DATA:
    #!/usr/bin/env bash
    echo "🔒 Encrypting string..."
    echo "{{DATA}}" | provisioning kms encrypt --backend rustyvault --stdin

@kms-decrypt-string ENCRYPTED:
    #!/usr/bin/env bash
    echo "🔓 Decrypting string..."
    echo "{{ENCRYPTED}}" | provisioning kms decrypt --stdin

@kms-encrypt-context FILE CONTEXT:
    #!/usr/bin/env bash
    echo "🔒 Encrypting {{FILE}} with context: {{CONTEXT}}..."
    provisioning kms encrypt {{FILE}} --backend rustyvault --context "{{CONTEXT}}"
    echo "✅ File encrypted with AAD"

# Backend Management
# ============================================================================

# List available KMS backends
@kms-backends:
    echo "📋 Available KMS Backends"
    echo "========================="
    provisioning kms backends

@kms-status:
    echo "📊 KMS Status"
    echo "============="
    provisioning kms status

@kms-test BACKEND="rustyvault":
    echo "🧪 Testing KMS backend: {{BACKEND}}"
    echo "===================================="
    provisioning kms test {{BACKEND}}

@kms-test-all:
    echo "🧪 Testing All KMS Backends"
    echo "============================"
    echo ""
    echo "Testing RustyVault..."
    provisioning kms test rustyvault || echo "❌ RustyVault failed"
    echo ""
    echo "Testing Age..."
    provisioning kms test age || echo "❌ Age failed"
    echo ""
    echo "Testing Vault..."
    provisioning kms test vault || echo "❌ Vault failed"
    echo ""
    echo "Testing Cosmian..."
    provisioning kms test cosmian || echo "❌ Cosmian failed"
    echo ""
    echo "Testing AWS KMS..."
    provisioning kms test aws-kms || echo "❌ AWS KMS failed"
    echo ""
    echo "✅ Backend testing complete"

@kms-switch-backend BACKEND:
    echo "🔄 Switching to {{BACKEND}} backend..."
    provisioning config set kms.backend {{BACKEND}}
    echo "✅ Default backend changed to {{BACKEND}}"

# Key Management
# ============================================================================

# Generate AES256 encryption key
@kms-generate-key:
    #!/usr/bin/env bash
    echo "🔑 Generating AES256 encryption key..."
    provisioning kms generate-key --spec AES256
    echo "✅ Key generated"

@kms-generate-key-spec SPEC:
    #!/usr/bin/env bash
    echo "🔑 Generating {{SPEC}} key..."
    provisioning kms generate-key --spec {{SPEC}}
    echo "✅ Key generated"

@kms-list-keys:
    echo "🔑 Encryption Keys"
    echo "=================="
    provisioning kms list-keys

@kms-key-info KEY_ID:
    echo "🔍 Key Information: {{KEY_ID}}"
    echo "=============================="
    provisioning kms key-info {{KEY_ID}}

@kms-rotate-key KEY_ID:
    echo "🔄 Rotating key: {{KEY_ID}}..."
    provisioning kms rotate-key {{KEY_ID}}
    echo "✅ Key rotated successfully"

@kms-delete-key KEY_ID:
    #!/usr/bin/env bash
    echo "🗑️  Deleting key: {{KEY_ID}}..."
    read -p "⚠️  This will permanently delete the key. Continue? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        provisioning kms delete-key {{KEY_ID}}
        echo "✅ Key deleted"
    else
        echo "❌ Cancelled"
    fi

# Configuration Encryption
# ============================================================================

# Encrypt configuration file (YAML/TOML)
@encrypt-config FILE:
    echo "🔒 Encrypting configuration: {{FILE}}..."
    provisioning config encrypt {{FILE}}
    echo "✅ Configuration encrypted"

@decrypt-config FILE:
    echo "🔓 Decrypting configuration: {{FILE}}..."
    provisioning config decrypt {{FILE}}
    echo "✅ Configuration decrypted"

@encrypt-config-inplace FILE:
    #!/usr/bin/env bash
    echo "🔒 Encrypting configuration in-place: {{FILE}}..."
    provisioning config encrypt {{FILE}} --in-place
    echo "✅ Configuration encrypted (original replaced)"

@view-encrypted-config FILE:
    #!/usr/bin/env bash
    echo "👁️  Viewing encrypted configuration: {{FILE}}"
    echo "=============================================="
    provisioning config decrypt {{FILE}} --stdout

# Bulk Operations
# ============================================================================

# Encrypt all .env files in directory
@encrypt-env-files DIR=".":
    #!/usr/bin/env bash
    echo "🔒 Encrypting all .env files in {{DIR}}..."
    find {{DIR}} -name "*.env" -type f -exec sh -c 'echo "Encrypting {}"; provisioning kms encrypt "{}" --backend rustyvault' \;
    echo "✅ All .env files encrypted"

@encrypt-configs DIR="config":
    echo "🔒 Encrypting all configs in {{DIR}}..."
    find {{DIR}} \( -name "*.yaml" -o -name "*.toml" \) -type f -exec sh -c 'echo "Encrypting {}"; provisioning config encrypt "{}"' \;
    echo "✅ All configurations encrypted"

@decrypt-all-files DIR:
    echo "🔓 Decrypting all encrypted files in {{DIR}}..."
    find {{DIR}} -name "*.enc" -type f -exec sh -c 'echo "Decrypting {}"; provisioning kms decrypt "{}"' \;
    echo "✅ All files decrypted"

@reencrypt-files DIR BACKEND:
    #!/usr/bin/env bash
    echo "🔄 Re-encrypting all files in {{DIR}} with {{BACKEND}}..."
    echo "⚠️  This will decrypt and re-encrypt all .enc files"
    read -p "Continue? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        find {{DIR}} -name "*.enc" -type f -exec sh -c 'f="{}"; provisioning kms decrypt "$f" && rm "$f" && provisioning kms encrypt "${f%.enc}" --backend {{BACKEND}}' \;
        echo "✅ Re-encryption complete"
    else
        echo "❌ Cancelled"
    fi

# Secrets Management Integration
# ============================================================================

# Encrypt secret value
@secret-encrypt NAME VALUE:
    #!/usr/bin/env bash
    echo "🔒 Encrypting secret: {{NAME}}..."
    echo "{{VALUE}}" | provisioning kms encrypt --backend rustyvault --stdin > "secrets/{{NAME}}.enc"
    echo "✅ Secret encrypted: secrets/{{NAME}}.enc"

@secret-decrypt NAME:
    #!/usr/bin/env bash
    echo "🔓 Decrypting secret: {{NAME}}..."
    provisioning kms decrypt "secrets/{{NAME}}.enc" --stdout

# Advanced Operations
# ============================================================================

# Encrypt with envelope encryption (AWS KMS style)
@kms-envelope-encrypt FILE:
    #!/usr/bin/env bash
    echo "🔒 Encrypting {{FILE}} with envelope encryption..."
    provisioning kms encrypt {{FILE}} --backend aws-kms --envelope
    echo "✅ File encrypted with envelope encryption"

@kms-verify FILE:
    echo "✅ Verifying encrypted file: {{FILE}}..."
    provisioning kms verify {{FILE}}

@kms-benchmark BACKEND="rustyvault":
    #!/usr/bin/env bash
    echo "📊 Benchmarking {{BACKEND}} backend..."
    provisioning kms benchmark --backend {{BACKEND}}

# Troubleshooting
# ============================================================================

# Test KMS connectivity and configuration
@kms-test-connectivity:
    echo "🧪 Testing KMS Connectivity"
    echo "============================"
    echo ""
    echo "1. Testing RustyVault (local)..."
    provisioning kms test rustyvault
    echo ""
    echo "2. Testing Vault connectivity..."
    provisioning kms test vault
    echo ""
    echo "3. Testing AWS KMS connectivity..."
    provisioning kms test aws-kms
    echo ""
    echo "✅ Connectivity test complete"

@kms-config:
    echo "⚙️  KMS Configuration"
    echo "====================="
    provisioning config get kms

@kms-diagnose:
    echo "🔍 KMS Diagnostics"
    echo "=================="
    echo ""
    echo "Current backend:"
    provisioning config get kms.backend
    echo ""
    echo "Backend status:"
    provisioning kms status
    echo ""
    echo "Available backends:"
    provisioning kms backends
    echo ""
    echo "✅ Diagnostics complete"

# Quick Workflows
# ============================================================================

# Quick encrypt workflow (encrypt file with default backend)
@quick-encrypt FILE:
    #!/usr/bin/env bash
    echo "⚡ Quick Encrypt: {{FILE}}"
    provisioning kms encrypt {{FILE}} --backend rustyvault
    echo "✅ Done: {{FILE}}.enc"

@quick-decrypt FILE:
    echo "⚡ Quick Decrypt: {{FILE}}"
    provisioning kms decrypt {{FILE}}
    echo "✅ Done"

@kms-setup:
    #!/usr/bin/env bash
    echo "🚀 Setting up KMS"
    echo "================="
    echo ""
    echo "1. Testing backends..."
    just kms-test-all
    echo ""
    echo "2. Generating encryption key..."
    provisioning kms generate-key --spec AES256
    echo ""
    echo "3. Creating secrets directory..."
    mkdir -p secrets
    echo ""
    echo "✅ KMS setup complete"
    echo ""
    echo "💡 Next steps:"
    echo "   - Encrypt configs: just encrypt-configs config/"
    echo "   - Encrypt secrets: just secret-encrypt NAME VALUE"

# Help
# ============================================================================

# Show KMS help
@kms-help:
    echo "🔐 KMS RECIPES"
    echo "=============="
    echo ""
    echo "🔒 ENCRYPTION OPERATIONS"
    echo "   just kms-encrypt <file>                - Encrypt file (RustyVault)"
    echo "   just kms-encrypt-backend <file> <be>   - Encrypt with specific backend"
    echo "   just kms-decrypt <file>                - Decrypt file"
    echo "   just kms-encrypt-string <data>         - Encrypt string inline"
    echo "   just kms-decrypt-string <encrypted>    - Decrypt string"
    echo "   just kms-encrypt-context <file> <ctx>  - Encrypt with AAD context"
    echo ""
    echo "🔧 BACKEND MANAGEMENT"
    echo "   just kms-backends                      - List available backends"
    echo "   just kms-status                        - Show backend status"
    echo "   just kms-test <backend>                - Test specific backend"
    echo "   just kms-test-all                      - Test all backends"
    echo "   just kms-switch-backend <backend>      - Change default backend"
    echo ""
    echo "🔑 KEY MANAGEMENT"
    echo "   just kms-generate-key                  - Generate AES256 key"
    echo "   just kms-generate-key-spec <spec>      - Generate key with spec"
    echo "   just kms-list-keys                     - List encryption keys"
    echo "   just kms-key-info <id>                 - Show key details"
    echo "   just kms-rotate-key <id>               - Rotate encryption key"
    echo "   just kms-delete-key <id>               - Delete key (careful!)"
    echo ""
    echo "⚙️  CONFIGURATION ENCRYPTION"
    echo "   just encrypt-config <file>             - Encrypt config file"
    echo "   just decrypt-config <file>             - Decrypt config file"
    echo "   just encrypt-config-inplace <file>     - Encrypt in-place"
    echo "   just view-encrypted-config <file>      - View without writing"
    echo ""
    echo "📦 BULK OPERATIONS"
    echo "   just encrypt-env-files [dir]           - Encrypt all .env files"
    echo "   just encrypt-configs [dir]             - Encrypt all configs"
    echo "   just decrypt-all-files <dir>           - Decrypt all .enc files"
    echo "   just reencrypt-files <dir> <backend>   - Re-encrypt with new backend"
    echo ""
    echo "🔐 SECRETS MANAGEMENT"
    echo "   just secret-encrypt <name> <value>     - Encrypt secret value"
    echo "   just secret-decrypt <name>             - Decrypt and show secret"
    echo ""
    echo "🚀 QUICK WORKFLOWS"
    echo "   just quick-encrypt <file>              - Fast encrypt"
    echo "   just quick-decrypt <file>              - Fast decrypt"
    echo "   just kms-setup                         - Setup KMS for project"
    echo ""
    echo "🔧 TROUBLESHOOTING"
    echo "   just kms-test-connectivity             - Test backend connectivity"
    echo "   just kms-config                        - Show configuration"
    echo "   just kms-diagnose                      - Diagnose issues"
    echo ""
    echo "📚 SUPPORTED BACKENDS"
    echo "   • rustyvault - Fast local encryption (default)"
    echo "   • age        - Age encryption (SOPS)"
    echo "   • vault      - HashiCorp Vault"
    echo "   • cosmian    - Cosmian KMS"
    echo "   • aws-kms    - AWS Key Management Service"
    echo ""
    echo "💡 EXAMPLES"
    echo "   # Encrypt configuration"
    echo "   just encrypt-config config/production.yaml"
    echo ""
    echo "   # Encrypt with AWS KMS"
    echo "   just kms-encrypt-backend secrets.json aws-kms"
    echo ""
    echo "   # Bulk encrypt environment files"
    echo "   just encrypt-env-files ."
    echo ""
    echo "   # Setup KMS for new project"
    echo "   just kms-setup"
