"""
This module manages key derivation and password prompts for File Vault.
It uses PBKDF2-HMAC-SHA256 to derive AES-256 keys from user-provided passwords.
"""

import os
import click
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend

# Constants for PBKDF2
ITERATIONS = 600000
KEY_LENGTH = 32  # 256 bits for AES-256
SALT_SIZE = 16   # 128 bits


def generate_salt() -> bytes:
    """
    Generates a cryptographically secure 16-byte salt.

    Returns:
        bytes: 16 random bytes from the OS.
    """
    return os.urandom(SALT_SIZE)


def derive_key(password: str, salt: bytes) -> bytes:
    """
    Derives a 256-bit key from a password and salt using PBKDF2-HMAC-SHA256.

    Args:
        password (str): The user's password.
        salt (bytes): The 16-byte salt associated with the file.

    Returns:
        bytes: A 32-byte key suitable for AES-256.
    """
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=KEY_LENGTH,
        salt=salt,
        iterations=ITERATIONS,
        backend=default_backend()
    )
    return kdf.derive(password.encode('utf-8'))


def prompt_decrypt_password() -> str:
    """
    Prompts the user for their decryption password without showing input.

    Returns:
        str: The entered password.
    """
    return click.prompt("Enter decryption password", hide_input=True)


def prompt_encrypt_password() -> str:
    """
    Prompts the user to set an encryption password with a confirmation prompt.

    Returns:
        str: The entered and confirmed password.
    """
    return click.prompt("Set encryption password", hide_input=True, confirmation_prompt=True)
