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

from __future__ import annotations

from pathlib import Path
from typing import Any

from peak.press.wrappers.publish.utils.env import (
    get_base_params,
    load_external_params,
    resolve_env_vars,
    resolve_path,
    to_bool,
)
from peak.press.wrappers.publish.utils.release_version import get_version
from peak.press.wrappers.publish.utils.spec import publish_spec


def publish_block(
    block: dict[str, Any],
    base_dir: str,
    app_params: dict[str, Any],
    existing_specs: list[dict[str, Any]],
) -> tuple[str, str]:
    """Publish a single block and return its ID and version."""
    name = block["name"]
    custom_params = resolve_env_vars(block.get("params", {}))
    external_params = load_external_params(name)

    version = get_version(
        existing_specs,
        name,
        custom_version=custom_params.get("VERSION"),
        increment=custom_params.get("increment_release_version", True),
        is_alpha=to_bool(custom_params.get("IS_ALPHA", False)),
    )
    if not version:
        msg = f"Block version could not be resolved for block: {name}"
        raise ValueError(msg)

    block_params = {
        **get_base_params(),
        **app_params,
        **external_params,
        **custom_params,
        "BLOCK_NAME": name,
        "VERSION": version,
    }

    block_id = publish_spec(
        existing_specs=existing_specs,
        spec_name=name,
        version=version,
        template_path=resolve_path(block["path"], Path(base_dir)),
        params=block_params,
        is_app=False,
    )

    return block_id, version
