#
# # Copyright © 2026 Peak AI Limited. or its affiliates. All Rights Reserved.
# #
# # Licensed under the Apache License, Version 2.0 (the "License"). You
# # may not use this file except in compliance with the License. A copy of
# # the License is located at:
# #
# # https://github.com/PeakBI/peak-sdk/blob/main/LICENSE
# #
# # or in the "license" file accompanying this file. This file is
# # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# # ANY KIND, either express or implied. See the License for the specific
# # language governing permissions and limitations under the License.
# #
# # This file is part of the peak-sdk.
# # see (https://github.com/PeakBI/peak-sdk)
# #
# # You should have received a copy of the APACHE LICENSE, VERSION 2.0
# # along with this program. If not, see <https://apache.org/licenses/LICENSE-2.0>
#
"""S3 upload operations."""

from __future__ import annotations

from pathlib import Path

from botocore.client import BaseClient  # type: ignore[import-not-found]

from peak.tools.s3.exists import object_exists


def upload_file(
    s3_client: BaseClient,
    bucket_name: str,
    destination_key: str,
    file_source: str,
    *,
    exist_ok: bool = False,
) -> None:
    """Upload file to s3.

    Parameters
    ----------
    s3_client:
        s3 client instance.
    bucket_name: str
        The s3 bucket name.
    destination_key: str
        The s3 key to upload the file to.
    file_source: str
        Path to the file to be uploaded.
    exist_ok: bool, optional
        If False, raise an error if a file at `destination_key` already exists
        before performing the upload. If True, do not raise an error.
        Default=False.
    """
    # source file inaccessible
    if not Path(file_source).exists():
        raise FileNotFoundError

    # cannot overwrite without permission
    if (not exist_ok) and object_exists(s3_client, bucket_name, destination_key):
        raise FileExistsError

    # actually do the upload
    s3_client.upload_file(file_source, bucket_name, destination_key)

    if not object_exists(s3_client, bucket_name, destination_key):
        msg = f"upload verification failure for '{bucket_name}/{destination_key}'."
        raise RuntimeError(msg)
