#
# # 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>
#
"""Utility functions for S3 operations."""

from __future__ import annotations

from pathlib import Path

from peak.tools.logging import LogLevel, PeakLogger, get_logger
from peak.tools.s3.s3 import S3

logger: PeakLogger = get_logger(level=LogLevel.INFO)


def upload_plugin_to_s3(plugin_path: str, app_name: str) -> str:
    """Upload a plugin file to S3.

    Args:
        plugin_path: Local file path of the plugin to upload
        app_name: Application name for S3 path construction

    Returns:
        S3 URI of the uploaded file

    Raises:
        RuntimeError: If the upload fails
    """
    s3 = S3()
    s3_key = f"{s3.root_prefix}datascience/plugins/{app_name}/{Path(plugin_path).name}"

    try:
        s3.upload(destination_key=s3_key, file_source=plugin_path, exist_ok=True)
    except (ValueError, OSError, RuntimeError) as e:
        error_msg = f"Failed to upload {plugin_path} to S3: {e}"
        logger.exception(error_msg)
        raise RuntimeError(error_msg) from e

    logger.info("Uploaded %s to s3://%s/%s", plugin_path, s3.bucket_name, s3_key)
    return f"s3://{s3.bucket_name}/{s3_key}"
