#
# # 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>
#
"""Runtime parameter fetching utilities."""

from __future__ import annotations

from os import environ
from pathlib import Path
from typing import Any

import yaml

from peak.press import blocks


def get_fallback_params(fallback_params_file: str) -> dict[str, Any]:
    """Get fallback parameters from a YAML file."""
    fallback_path = Path(fallback_params_file)
    if not fallback_path.exists():
        msg = f"Fallback params file not found at: {fallback_params_file}"
        raise FileNotFoundError(msg)

    with fallback_path.open() as f:
        return yaml.safe_load(f) or {}


def filter_keys_to_fetch(params: dict[str, Any], keys_to_fetch: list[str] | None) -> dict[str, Any]:
    """Filter parameters to only include specified keys."""
    if not keys_to_fetch:
        return params
    return {k: v for k, v in params.items() if k in keys_to_fetch}


def fetch_run_time_params(
    logger: Any,
    keys_to_fetch: list[str] | None = None,
    fallback_params_file: str = "",
) -> dict[str, Any]:
    """Fetch runtime parameters from the deployment or fallback file."""
    try:
        blocks_client = blocks.get_client()
        parameters = blocks_client.get_parameters(
            deployment_id=environ.get("PRESS_DEPLOYMENT_ID"),
            fallback_params_file=fallback_params_file,
        )

        return filter_keys_to_fetch(parameters, keys_to_fetch)
    except (ValueError, KeyError, RuntimeError):
        logger.exception("Failed to fetch run time parameters, using default parameters")
        params = get_fallback_params(fallback_params_file)
        return filter_keys_to_fetch(params, keys_to_fetch)
