#
# # 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>
#
"""Simple Jinja2 config template compiler."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Any

from jinja2 import Environment, FileSystemLoader


def get_instance_options(*resource_types: str) -> tuple[list[dict[str, str]], ...]:
    """Get instance options for one or more resource types.

    Args:
        *resource_types: Resource types (api-deployment, data-bridge, webapp, workflow, workspace)

    Returns:
        Tuple of lists with instance option dicts (label, value) per resource type
    """
    from peak.resources import tenants

    def fetch_instances(client: Any, rtype: str) -> list[dict[str, str]]:
        """Fetch instances for a single resource type."""
        try:
            resource_instances = client.list_instance_options(rtype)["data"]
            return [{"label": instance["name"], "value": instance["id"]} for instance in resource_instances]
        except (ValueError, KeyError, RuntimeError):
            return []

    client = tenants.get_client()
    return tuple(fetch_instances(client, rtype) for rtype in resource_types)


def compile_jinja_config(
    config_path: str,
    output_path: str | None = None,
    context: dict[str, Any] | None = None,
) -> str:
    """Compile a Jinja2 config template to YAML.

    Args:
        config_path: Path to the Jinja2 template (.j2 or .jinja2)
        output_path: Optional output path. If not provided, strips .j2/.jinja2 extension
        context: Optional context dictionary. If not provided, uses environment variables

    Returns:
        Path to the compiled YAML file

    Raises:
        FileNotFoundError: If template doesn't exist
    """
    config_path_obj = Path(config_path)

    # Skip if not a J2 template
    if not str(config_path_obj).endswith((".j2", ".jinja2")):
        return config_path

    if not config_path_obj.exists():
        msg = f"Config template not found: {config_path}"
        raise FileNotFoundError(msg)

    if context is None:
        context = dict(os.environ)

    if "SUFFIX" in context:
        context["SPEC_SUFFIX"] = context["SUFFIX"]

        if os.environ.get("PEAK_AUTH_TOKEN"):
            try:
                workflow_instances, webapp_instances, api_instances = get_instance_options(
                    "workflow",
                    "webapp",
                    "api-deployment",
                )
                context.update(
                    {
                        "WORKFLOW_INSTANCES": workflow_instances,
                        "WEBAPP_INSTANCES": webapp_instances,
                        "API_INSTANCES": api_instances,
                    },
                )
            except (ValueError, KeyError, RuntimeError):
                context.update(
                    {
                        "WORKFLOW_INSTANCES": [],
                        "WEBAPP_INSTANCES": [],
                        "API_INSTANCES": [],
                    },
                )

    # Render template
    env = Environment(loader=FileSystemLoader(config_path_obj.parent), autoescape=True)
    template = env.get_template(config_path_obj.name)
    rendered = template.render(**context)

    # Determine output path
    if output_path is None:
        output_path = str(config_path_obj)
        if output_path.endswith(".j2"):
            output_path = output_path[:-3]
        elif output_path.endswith(".jinja2"):
            output_path = output_path[:-7]

    output_path_obj = Path(output_path)
    output_path_obj.parent.mkdir(parents=True, exist_ok=True)
    output_path_obj.write_text(rendered)

    return str(output_path_obj)
