from Crypto.Cipher import AES
import base64
import os
from .config_local import CRYPTO_KEY

class EncryptionUtil:

    def __init__(self, key):
        # In a real application, store this key securely (e.g., environment variables)
        self.crypto_key = key

    def encrypt_aes_gcm(self, plaintext):
        # Decode the base64 encoded key
        key = base64.b64decode(self.crypto_key)

        # Generate a random 12-byte nonce
        nonce = os.urandom(12)

        # Create the cipher object
        cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)

        # Encrypt the plaintext
        ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode('utf-8'))

        # Combine nonce, ciphertext, and tag
        encrypted_data = nonce + ciphertext + tag

        # Encode the result in base64
        encrypted_base64 = base64.b64encode(encrypted_data).decode('utf-8')

        return encrypted_base64

    def decrypt_aes_gcm(self, encrypted_base64):
        # Decode the base64 encoded data and key
        encrypted_data = base64.b64decode(encrypted_base64)
        key = base64.b64decode(self.crypto_key)

        # Extract the nonce, tag, and ciphertext from the combined encrypted data
        nonce = encrypted_data[:12]        # AES GCM nonce is 12 bytes
        tag = encrypted_data[-16:]         # AES GCM tag is 16 bytes
        ciphertext = encrypted_data[12:-16] # Ciphertext is everything in between

        # Create the cipher object and decrypt the data
        cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
        decrypted_data = cipher.decrypt_and_verify(ciphertext, tag)

        # Convert decrypted bytes to string (assuming UTF-8 encoding)
        decrypted_text = decrypted_data.decode('utf-8')
        return decrypted_text

encryption_util = EncryptionUtil(CRYPTO_KEY)
