#
# # 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>
#
"""Deployment metadata retrieval utilities."""

from __future__ import annotations

from typing import Any

from peak.exceptions import (
    BadRequestException,
    ForbiddenException,
    InternalServerErrorException,
    NotFoundException,
    UnauthorizedException,
)
from peak.press import apps
from peak.resources import services

apps_client = apps.get_client()
services_client = services.get_client()


def get_deployment_metadata(deployed_app_id: str) -> dict[str, Any]:
    """Retrieve the metadata of a deployed application.

    Args:
        deployed_app_id: The deployed application ID

    Returns:
        The deployment metadata dictionary

    Raises:
        RuntimeError: If API call fails
        KeyError: If deployment or metadata not found
    """
    try:
        deployed_app = apps_client.describe_deployment(deployed_app_id)
    except (
        BadRequestException,
        UnauthorizedException,
        ForbiddenException,
        NotFoundException,
        InternalServerErrorException,
    ) as e:
        msg = f"Failed to describe deployment {deployed_app_id}: {e!s}"
        raise RuntimeError(msg) from e
    if not deployed_app:
        msg = f"Deployment {deployed_app_id} not found"
        raise KeyError(msg)
    deployed_app_metadata = deployed_app.get("metadata", {})
    if not deployed_app_metadata:
        msg = f"No name found for deployment {deployed_app_id}"
        raise KeyError(msg)
    return dict(deployed_app_metadata)
