"""
Работа с сессиями s3 хранилища
"""

from asyncio import to_thread
from functools import wraps
from typing import Callable

from botocore.client import BaseClient, Config
from botocore.session import Session

from s3_manager.s3storage.config import get_s3_client_config
from s3_manager.s3storage.content_hash import add_md5_header


def get_s3_client() -> BaseClient:
    """
    Инверсия на получение сессиии S3

    :return:
    """
    session: Session = Session()

    cfg = get_s3_client_config()

    client = session.create_client(
        service_name="s3",
        aws_access_key_id=cfg.ACCESS_KEY,
        aws_secret_access_key=cfg.SECRET_KEY,
        endpoint_url=cfg.ENDPOINT,
        region_name="spb99",
        config=Config(
            signature_version="s3v4",
            s3={
                "addressing_style": "path",
                "payload_signing_enabled": True,
            },
        ),
        verify=cfg.SSL_CA_BUNDLE_PATH,
    )

    client.meta.events.register("request-created.s3", add_md5_header)

    return client


def s3_client_wrapper(func: Callable) -> Callable:
    """
    Декоратор клиента s3
    """

    @wraps(func)
    async def wrapper(*args, **kwargs) -> Callable:
        s3_client = get_s3_client()
        try:
            return await to_thread(func, s3_client=s3_client, *args, **kwargs)
        finally:
            s3_client.close()

    return wrapper
