import zstandard
from csirtmu.core.temporal.s3 import S3Config
from minio import Minio


def load_perun_data_from_s3(config: S3Config, s3_key: str) -> str:
    client: Minio = Minio(
        config.host,
        access_key=config.access_key,
        secret_key=config.secret_key,
        cert_check=False,
        secure=config.secure,
    )

    # Get data of an object.
    response = None
    try:
        response = client.get_object(config.bucket, s3_key)
        response_data = response.read()
    finally:
        if response:
            response.close()
            response.release_conn()

    # TODO better check (e.g. based on content type of a response)
    if s3_key.endswith(".json"):
        raw_data = response_data.decode("utf-8")
    elif s3_key.endswith(".zst"):
        zd = zstandard.ZstdDecompressor()
        stream_reader = zd.stream_reader(response_data)
        raw_data = stream_reader.readall().decode("utf-8")
    else:
        raise ValueError(f"Unsupported file type {s3_key}.")

    return raw_data
