#
# # 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 triggering utilities."""

from __future__ import annotations

from typing import Any

from peak.press import blocks
from peak.resources import workflows
from peak.tools.logging import LogLevel, PeakLogger, get_logger

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


def get_workflow_name(deployment_data: dict[str, Any]) -> str | None:
    """Get the workflow name from deployment data."""
    for resource in deployment_data.get("latestRevision", {}).get("resources", []):
        if resource.get("kind") == "workflow":
            name = resource.get("name")
            logger.info("[Current Workflow] Found: %s", name)
            return str(name) if name else None
    logger.error("[Current Workflow] No workflow found in deployment data.")
    return None


def get_next_workflow_name(
    current_workflow: str,
    workflows_list: list[str],
    block_list: list[dict[str, Any]],
) -> str | None:
    """Get the next workflow name in sequence."""
    try:
        current_index = next(i for i, prefix in enumerate(workflows_list) if current_workflow.startswith(prefix))
        next_prefix = workflows_list[current_index + 1]
    except (StopIteration, IndexError):
        logger.warning("[Next Workflow] No next workflow found after: %s", current_workflow)
        return None

    for block in block_list:
        if block.get("kind") == "workflow" and block.get("name", "").startswith(next_prefix):
            name = block["name"]
            logger.info("[Next Workflow] Determined: %s", name)
            return str(name)

    logger.error("[Next Workflow] Block not found with prefix: %s", next_prefix)
    return None


def trigger_workflow(workflow_name: str, press_deployment_id: str, *, trigger_once: bool = False) -> str:
    """Trigger a workflow by name."""
    blocks_client = blocks.get_client()
    workflow_client = workflows.get_client()

    for block in blocks_client.get_related_block_details(press_deployment_id):
        if block.get("kind") != "workflow" or workflow_name not in block.get("name", ""):
            continue

        workflow_id = block["resource_id"]
        if trigger_once:
            executions = workflow_client.list_executions(workflow_id, return_iterator=False)
            if executions.get("executionsCount", 0) > 0:
                logger.info("[Trigger] %s already executed. Skipping.", workflow_name)
                return f"{workflow_name} already executed"

        logger.info("[Trigger] Executing workflow: %s", workflow_name)
        workflow_client.execute_workflow(workflow_id)
        return f"{workflow_name} triggered"

    logger.error("[Trigger] No matching workflow found for: %s", workflow_name)
    return f"No matching workflow found for {workflow_name}"
