from io import BytesIO

from botocore.client import BaseClient

from s3_manager.s3storage.schema import FileMetaData
from s3_manager.s3storage.session import s3_client_wrapper


@s3_client_wrapper
def s3_get_file_chunk(
    s3_client: BaseClient,
    obj_key: str,
    s3bucket: str,
    start_byte: int,
    end_byte: int,
) -> BytesIO:
    """
    Прочитать файл
    """
    try:
        response = s3_client.get_object(
            Bucket=s3bucket,
            Key=obj_key,
            Range=f"bytes={start_byte}-{end_byte}",
        )
        return BytesIO(response["Body"].read())
    except Exception:
        return BytesIO(b"")


@s3_client_wrapper
def s3_get_file_metadata(
    s3_client: BaseClient,
    obj_key: str,
    s3bucket: str,
) -> FileMetaData:
    """
    Получить метаданные объека s3
    """
    obj = s3_client.head_object(
        Bucket=s3bucket,
        Key=obj_key,
    )

    return FileMetaData(
        file_size=obj.get("ContentLength"),
        content_type=obj.get("ContentType"),
        last_modified=obj.get("LastModified"),
    )
