import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from core.config import get_settings
from core.exceptions import CryptoError


def encrypt_string(plaintext: str, key_version: int | None = None) -> tuple[str, int]:
    """
    Encrypt a plaintext string using AES-256-GCM.
    Returns (base64_encoded_payload, key_version).
    Payload format: 12-byte nonce + 16-byte tag + ciphertext (handled by AESGCM).
    """
    if not plaintext:
        raise CryptoError("Cannot encrypt empty string")

    settings = get_settings()
    current_key_version = key_version or settings.ENCRYPTION_KEY_VERSION
    key = settings.raw_encryption_key

    try:
        aesgcm = AESGCM(key)
        nonce = os.urandom(12)  # 96-bit nonce for GCM
        # AESGCM.encrypt appends 16-byte auth tag at the end of ciphertext
        ciphertext = aesgcm.encrypt(nonce, plaintext.encode("utf-8"), None)
        payload = nonce + ciphertext
        return base64.b64encode(payload).decode("ascii"), current_key_version
    except Exception as exc:
        raise CryptoError(f"Encryption failed: {exc}") from exc


def decrypt_string(encrypted_payload_b64: str, key_version: int | None = None) -> str:
    """
    Decrypt a base64-encoded AES-256-GCM payload.
    """
    if not encrypted_payload_b64:
        raise CryptoError("Cannot decrypt empty payload")

    settings = get_settings()
    key = settings.raw_encryption_key

    try:
        raw_payload = base64.b64decode(encrypted_payload_b64)
        if len(raw_payload) < 28:  # 12 bytes nonce + 16 bytes tag minimum
            raise CryptoError("Payload is too short to be valid AES-GCM ciphertext")

        nonce = raw_payload[:12]
        ciphertext = raw_payload[12:]

        aesgcm = AESGCM(key)
        plaintext_bytes = aesgcm.decrypt(nonce, ciphertext, None)
        return plaintext_bytes.decode("utf-8")
    except Exception as exc:
        raise CryptoError(f"Decryption failed: {exc}") from exc
