from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from base64 import b64decode

def aes_cbc_base64_dec(key: str, iv: str, cipher_text: str) -> str:
    """
    Decrypts KIS WebSocket data using AES-256-CBC.
    adapted from KIS official sample.
    """
    if not key or not iv:
        raise ValueError("Key and IV are required for decryption")

    # Key and IV are assumed to be utf-8 strings
    cipher = AES.new(key.encode("utf-8"), AES.MODE_CBC, iv.encode("utf-8"))
    
    # Decrypt and unpad
    decrypted_bytes = unpad(cipher.decrypt(b64decode(cipher_text)), AES.block_size)
    
    return bytes.decode(decrypted_bytes, 'utf-8')
