"""Contains all protection utils."""

import logging
from pathlib import Path

import requests

_logger = logging.getLogger(__name__)


def protect_file(  # noqa: PLR0913
    *,
    file_path: Path,
    file_type: str,
    identifier: str,
    api_endpoint: str,
    access_key_id: str,
    access_secret_key: str,
    replace: bool,
) -> None:
    """Protect a file using the protector service.

    Args:
        file_path: Path to the file to protect
        file_type: Type of file to protect ('python' for wheels, 'elf' for ELF binaries)
        identifier: Protection identifier (e.g., 'dev-software-py-package-1')
        api_endpoint: The protector API endpoint
        access_key_id: Access key ID for authentication
        access_secret_key: Access secret key for authentication
        replace: If True, replace the original file with the encrypted version
    """
    url = f"{api_endpoint.rstrip('/')}/encrypt/{file_type}"

    _logger.info("Sending file '%s' to '%s' for encryption", file_path, url)

    with file_path.open("rb") as file_handler:
        response = requests.post(
            url,
            headers={"access_key_id": access_key_id, "access_secret_key": access_secret_key},
            params={"identifier": identifier},
            files={"file": file_handler},
            timeout=60,
        )
        response.raise_for_status()

    output_file = file_path if replace else file_path.parent / f"{file_path.stem}_encrypted{file_path.suffix}"

    _logger.info("Writing protected file to '%s'", output_file)

    with output_file.open("wb") as file_handler:
        file_handler.write(response.content)

    # For ELF files, add executable permissions
    if file_type == "elf":
        output_file.chmod(output_file.stat().st_mode | 0o111)
