"""KMS encryption service for sensitive data."""

import boto3
import base64
import logging
from typing import Optional
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


class PaymentEncryptor:
    """KMS encryption service for payment data."""
    
    def __init__(self, kms_key_id: str, region: str = "us-east-1"):
        self.kms_key_id = kms_key_id
        self.region = region
        self.kms_client = boto3.client("kms", region_name=region)
        logger.info(f"PaymentEncryptor initialized with key: {kms_key_id}")
    
    def encrypt(self, plaintext: str) -> Optional[str]:
        """Encrypt sensitive data using KMS."""
        try:
            response = self.kms_client.encrypt(
                KeyId=self.kms_key_id,
                Plaintext=plaintext.encode('utf-8')
            )
            
            encrypted_data = base64.b64encode(response['CiphertextBlob']).decode('utf-8')
            logger.info("Data encrypted successfully")
            return encrypted_data
        except ClientError as e:
            logger.error(f"KMS encryption failed: {e}")
            return None
    
    def decrypt(self, encrypted_data: str) -> Optional[str]:
        """Decrypt data using KMS."""
        try:
            ciphertext_blob = base64.b64decode(encrypted_data.encode('utf-8'))
            
            response = self.kms_client.decrypt(CiphertextBlob=ciphertext_blob)
            
            plaintext = response['Plaintext'].decode('utf-8')
            logger.info("Data decrypted successfully")
            return plaintext
        except ClientError as e:
            logger.error(f"KMS decryption failed: {e}")
            return None
