"""
Encryption/Decryption utilities for beach designer app compatibility
"""
import json
import base64
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import os

# AES encryption key and IV - should match the frontend
KEY = b'0123456789abcedf0123456789abcedf'  # 32 bytes for AES-256
IV = b'0123456789abcedf'  # 16 bytes for AES block size

def Encrypt(data: dict) -> str:
    """Encrypt data to match frontend format (AES/CBC/PKCS7)"""
    try:
        # Convert data to JSON string
        json_string = json.dumps(data)
        
        # Convert to bytes
        data_bytes = json_string.encode('utf-8')
        
        # Pad data to be multiple of 16 bytes (AES block size)
        padder = padding.PKCS7(128).padder()
        padded_data = padder.update(data_bytes)
        padded_data += padder.finalize()
        
        # Encrypt with AES-CBC
        cipher = Cipher(algorithms.AES(KEY), modes.CBC(IV), backend=default_backend())
        encryptor = cipher.encryptor()
        encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
        
        # Convert to base64 to match frontend format
        # First convert to base64 string of the ciphertext
        ciphertext_b64 = base64.b64encode(encrypted_data).decode('utf-8')
        
        # Then convert that to UTF-8 bytes and then to base64 again (to match frontend)
        utf8_bytes = ciphertext_b64.encode('utf-8')
        final_b64 = base64.b64encode(utf8_bytes).decode('utf-8')
        
        return final_b64
        
    except Exception as e:
        print(f"Encryption error: {e}")
        return ""

def Decrypt(encrypted_data: str) -> dict:
    """Decrypt data from frontend format (AES/CBC/PKCS7)"""
    try:
        # First decode from base64 (reverse the frontend process)
        utf8_b64_bytes = base64.b64decode(encrypted_data.encode('utf-8'))
        ciphertext_b64 = utf8_b64_bytes.decode('utf-8')
        
        # Then decode the actual ciphertext
        encrypted_bytes = base64.b64decode(ciphertext_b64.encode('utf-8'))
        
        # Decrypt with AES-CBC
        cipher = Cipher(algorithms.AES(KEY), modes.CBC(IV), backend=default_backend())
        decryptor = cipher.decryptor()
        padded_data = decryptor.update(encrypted_bytes) + decryptor.finalize()
        
        # Remove padding
        unpadder = padding.PKCS7(128).unpadder()
        data_bytes = unpadder.update(padded_data)
        data_bytes += unpadder.finalize()
        
        # Parse JSON
        json_string = data_bytes.decode('utf-8')
        data = json.loads(json_string)
        
        return data
        
    except Exception as e:
        print(f"Decryption error: {e}")
        # Try to parse as plain JSON (fallback)
        try:
            return json.loads(encrypted_data)
        except:
            return {}

def is_encrypted(data: str) -> bool:
    """Check if data appears to be encrypted"""
    try:
        # Try to decode as base64
        base64.b64decode(data.encode('utf-8'))
        return True
    except:
        return False