import copy
import os
import platform
import tempfile
import textwrap
import traceback
from pathlib import PurePosixPath, PurePath


def _setup_ssl() -> None:
    if not (platform.system() == "Windows" and platform.architecture()[0] == "64bit"):
        return None

    previous = copy.deepcopy(os.environ)
    try:
        python_folder = PurePath(__file__).parents[3]
        engines_folder = python_folder / "DLLs" / "engines-3"
        gost_dll = engines_folder / 'gost.dll'
        dynamic_path = PurePosixPath(gost_dll.as_posix())

        text = f"""\
        openssl_conf=openssl_gost
        [openssl_gost]
        engines = engine_section
        [engine_section]
        gost = gost_section
        [gost_section]
        engine_id = gost
        dynamic_path = "{str(dynamic_path)}"
        default_algorithms = ALL
        CRYPT_PARAMS = id-Gost28147-89-CryptoPro-A-ParamSet
        """
        text = textwrap.dedent(text)

        with tempfile.TemporaryDirectory() as tmpdir:
            openssl_cnf = os.path.join(tmpdir, "openssl.cnf")
            with open(openssl_cnf, mode="w", encoding="UTF-8") as f:
                f.write(text)
            os.environ['OPENSSL_CONF'] = openssl_cnf
            os.environ['OPENSSL_ENGINES'] = str(engines_folder)
            import ssl

    except (Exception,):
        traceback.print_exc()
    finally:
        os.environ = previous
