#
# # 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 configuration handling functions."""

from __future__ import annotations

from typing import Any


def add_block_swap_configuration(
    deployment_config: dict[str, Any],
    app_blocks: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    """Process includes and excludes in deployment config to modify app blocks.

    Args:
        deployment_config: Deployment config with includes/excludes specs
        app_blocks: Application blocks to be modified

    Returns:
        Modified app blocks list
    """
    if "includes" in deployment_config["spec"]:
        for include_block in deployment_config["spec"]["includes"]:
            # Only add if not already present (by id)
            if not any(block["id"] == include_block["id"] for block in app_blocks):
                app_blocks.append(
                    {
                        "id": include_block["id"],
                        "release": {"version": include_block["releaseVersion"]},
                    },
                )

    if "excludes" in deployment_config["spec"]:
        for exclude_block in deployment_config["spec"]["excludes"]:
            # Remove any blocks that are in the excludes list
            app_blocks = [block for block in app_blocks if block["id"] != exclude_block["id"]]

    # Return the modified blocks list
    return app_blocks


def prepare_revision_body(final_body: dict[str, Any]) -> dict[str, Any]:
    """Prepare the revision body for updating an existing deployment.

    Args:
        final_body: The final deployment configuration

    Returns:
        Prepared revision body for the deployment update
    """
    revision_body = {
        "appParameters": final_body["appParameters"],
        "parameters": final_body["parameters"],
        "revision": final_body["revision"],
        "release": final_body["spec"]["release"],
    }

    # Handle includes and excludes if present
    includes = final_body["spec"].get("includes")
    excludes = final_body["spec"].get("excludes")
    if includes is not None or excludes is not None:
        revision_body["blocksConfig"] = {}
        if includes is not None:
            revision_body["blocksConfig"]["includes"] = includes
        if excludes is not None:
            revision_body["blocksConfig"]["excludes"] = excludes

    return revision_body


def find_deployment(deployments: list[dict[str, Any]], spec_id: str) -> dict[str, Any] | None:
    """Find a deployment matching the given spec ID.

    Args:
        deployments: List of deployment dictionaries
        spec_id: The spec ID to search for

    Returns:
        Matching deployment dict, or None if not found
    """
    for deployment in deployments:
        if "spec" in deployment and deployment["spec"]["id"] == spec_id:
            return dict(deployment)
    return None
