#
# # 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>
#
"""Trigger next workflow in sequence."""

from __future__ import annotations

from peak.press import blocks
from peak.press.wrappers.orchestrator.trigger import get_next_workflow_name, get_workflow_name, trigger_workflow
from peak.tools.logging import LogLevel, PeakLogger, get_logger

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


def trigger_next_workflow(press_deployment_id: str, workflow_order: list[str]) -> str:
    """Identify and trigger the next workflow in the defined sequence.

    Args:
        press_deployment_id: The PRESS deployment ID
        workflow_order: List of workflow name prefixes defining execution order

    Returns:
        Message indicating success or error
    """
    blocks_client = blocks.get_client()

    deployment = blocks_client.describe_deployment(press_deployment_id)
    current_workflow = get_workflow_name(deployment)
    if not current_workflow:
        return "[TriggerNext] Current workflow not found."

    if not workflow_order:
        logger.error("[TriggerNext] WORKFLOW_ORDER not defined in parameters.")
        return "[TriggerNext] WORKFLOW_ORDER missing."

    related_blocks = blocks_client.get_related_block_details(press_deployment_id)
    next_workflow = get_next_workflow_name(current_workflow, workflow_order, related_blocks)

    if not next_workflow:
        return f"[TriggerNext] No next workflow found after {current_workflow}"

    return trigger_workflow(next_workflow, press_deployment_id)
