import base64
from pathlib import Path
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

def decrypt_file(enc_path: str, encryption_key: str):
    """
    Decrypts a .zip.enc file encrypted with AES-256-GCM.

    Args:
        enc_path (str): Path to the encrypted file (.zip.enc)
        encryption_key (str): 43-character base64-url AES key
    """
    enc_file = Path(enc_path)
    if not enc_file.exists():
        raise FileNotFoundError(f"File not found: {enc_path}")

    if enc_file.suffix == ".enc":
        out_file = enc_file.with_suffix("")  # removes .enc
    else:
        out_file = enc_file.with_suffix(".zip")

    # Decode base64-url key
    key_bytes = base64.urlsafe_b64decode(encryption_key)

    # Read data
    data = enc_file.read_bytes()
    if len(data) < 28:
        raise ValueError("Encrypted file too short or corrupted.")

    nonce = data[:12]
    tag = data[12:28]
    ciphertext = data[28:]

    cipher = Cipher(algorithms.AES(key_bytes), modes.GCM(nonce, tag), backend=default_backend())
    decryptor = cipher.decryptor()
    plaintext = decryptor.update(ciphertext) + decryptor.finalize()

    out_file.write_bytes(plaintext)
    return str(out_file)
