#
# # 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>
#
"""Workflow status 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, workflows

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


def get_workflow_status(deployed_app_id: str, workflow_name: str) -> str:
    """Retrieve the status of a workflow.

    Args:
        deployed_app_id: The deployed application ID
        workflow_name: Name of the workflow to check

    Returns:
        The workflow status string

    Raises:
        RuntimeError: If API calls fail
        KeyError: If deployment or workflow not found
        ValueError: If workflow details or blocks not found
    """
    try:
        deployed_app = apps_client.describe_deployment(deployment_id=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 ValueError(msg)

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

    if not workflow_id:
        msg = f"Workflow {workflow_name} not found in deployment {deployed_app_id}"
        raise KeyError(msg)
    try:
        workflow_details = workflow_client.describe_workflow(workflow_id)
    except (
        BadRequestException,
        UnauthorizedException,
        ForbiddenException,
        NotFoundException,
        InternalServerErrorException,
        UnprocessableEntityException,
    ) as e:
        msg = f"Failed to describe workflow {workflow_id}: {e!s}"
        raise RuntimeError(msg) from e
    if not workflow_details:
        msg = f"Workflow {workflow_id} details not found"
        raise ValueError(msg)
    workflow_status = workflow_details.get("lastExecution", {"status": "unknown"})
    return str(workflow_status.get("status", "unknown"))
