from pathlib import Path
from subprocess import call
from shutil import move, copy
from os import PathLike
from random import randint
from akademiya.constants import PLATFORM_DIRS
from akademiya.internal import utils as _utils


def decrypt_book_file(book_file: PathLike, out_path: PathLike):
    """
    Decrypts the book file, only works if the book is downloaded by this client.

    Args:
        book_file (PathLike): The path to the encrypted book file.

    Returns:
        bytes: The decrypted book data.
    """
    cache_path = PLATFORM_DIRS.site_cache_path
    cache_path.mkdir(exist_ok=True)
    random_name_input = str(randint(100000, 999999))
    input_file = cache_path.joinpath(random_name_input)
    random_name_output = str(randint(100000, 999999))
    output_file = cache_path.joinpath(random_name_output)
    copy(book_file, input_file)
    window_id = _utils.calculate_window_id()
    retcode = call(["./bin/decypherer.exe", window_id, str(input_file), str(output_file)])
    Path(input_file).unlink()
    if retcode != 0:
        raise RuntimeError("Failed to decrypt the book file.")
    move(output_file, out_path)
