#
# # 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>
#
"""Service URL retrieval utilities."""

from __future__ import annotations

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

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


def get_service_url(deployed_app_id: str, name: str) -> str:
    """Retrieve the application URL for a webapp block in a deployed application.

    Args:
        deployed_app_id: The deployed application ID
        name: Substring to match against webapp block names

    Returns:
        Application URL of the matching webapp service

    Raises:
        RuntimeError: If API calls fail
        KeyError: If no matching webapp block is found
        ValueError: If deployment, blocks, or service URL 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)

    block_list = deployed_app.get("latestRevision", {}).get("blocks", [])

    if not block_list:
        msg = f"No blocks found in deployment {deployed_app_id}"
        raise KeyError(msg)

    webapp_id = None
    for block in block_list:
        if name in block.get("name", ""):
            webapp_id = block.get("platformId")
            break

    if not webapp_id:
        msg = f"No webapp block found with name containing '{name}' in deployment {deployed_app_id}"
        raise KeyError(msg)

    try:
        service_info = services_client.describe_service(webapp_id)
    except (
        UnauthorizedException,
        ForbiddenException,
        NotFoundException,
        UnprocessableEntityException,
        InternalServerErrorException,
    ) as e:
        msg = f"Failed to describe service {webapp_id}: {e!s}"
        raise RuntimeError(msg) from e

    if not service_info:
        msg = f"Service {webapp_id} not found"
        raise ValueError(msg)

    application_url = service_info.get("applicationUrl")
    if not application_url:
        msg = f"No applicationUrl found for service {webapp_id}"
        raise ValueError(msg)

    return str(application_url)
