from pathlib import Path
# from base64 import b64encode
from httpx import Client

import encryption


PASSWORD = input("Password: ").strip()


ENCODING = "utf-8"

current_dirpath = Path(__file__).resolve().parent
dist_dirpath = current_dirpath / "dist"
http_client = Client()


if not dist_dirpath.exists():
    dist_dirpath.mkdir()


def minify_js(js_code: str) -> str:
    response = http_client.post(
        "https://www.toptal.com/developers/javascript-minifier/api/raw",
        data = {
            "input": js_code
        }
    )

    return response.text


def inherit_saver(file_paths: list[tuple[Path, bool]]) -> None:
    if len(file_paths) < 2:
        print("Not enough files provided for hierarchy encoding.")

        return

    for index, (file_path, _) in enumerate(file_paths):
        if index == 0:
            (dist_dirpath / file_path.name).write_text(file_path.read_text(ENCODING))

            continue

        minified_file_content = minify_js((dist_dirpath / file_paths[index - 1][0].name).read_text(ENCODING))

        (dist_dirpath / file_path.name).write_text(
            file_path.read_text(ENCODING).replace(
                ".....",
                (
                    encryption.encrypt_message_text(
                        message_text = minified_file_content,
                        password = PASSWORD
                    )
                    if file_paths[index - 1][1]
                    else
                    minified_file_content
                ),
                1
            )
        )

    # file_path = file_paths[-1][0]

    # txt_filepath = dist_dirpath / (file_path.name + ".txt")

    # txt_filepath.write_text(b64encode(
    #     (dist_dirpath / file_path.name).read_text(ENCODING).encode(ENCODING)
    # ).decode(ENCODING))

    # print(f"All files saved to [{dist_dirpath}]: {[file_path[0].name for file_path in file_paths]}")
    # print(f"Final .txt file saved: {txt_filepath.resolve()}")


if __name__ == "__main__":
    inherit_saver([
        # (target, must_be_encrypted_for_next_file_replace)
        (current_dirpath / "worker.js", True),
        (current_dirpath / "executor.js", False),
    ])
