#
# Copyright 2025 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
#
from typing import Union, Optional

from splunk_add_on_ucc_framework.commands.rest_builder.endpoint.base import (
    RestEndpointBuilder,
)
from splunk_add_on_ucc_framework.commands.rest_builder.user_defined_rest_handlers import (
    EndpointRegistrationEntry,
)
from splunk_add_on_ucc_framework.generators.file_generator import FileGenerator
from splunk_add_on_ucc_framework.global_config import GlobalConfig


class RestMapConf(FileGenerator):
    __description__ = (
        "Generates `restmap.conf` for the custom REST handlers that "
        "are generated based on configs from globalConfig"
    )

    def __init__(
        self, global_config: GlobalConfig, input_dir: str, output_dir: str
    ) -> None:
        super().__init__(global_config, input_dir, output_dir)
        self.conf_file = "restmap.conf"
        self.endpoints: list[Union[RestEndpointBuilder, EndpointRegistrationEntry]] = []
        self.configuration_endpoints: list[
            Union[RestEndpointBuilder, EndpointRegistrationEntry]
        ] = []
        self.inputs_endpoints: list[
            Union[RestEndpointBuilder, EndpointRegistrationEntry]
        ] = []
        self.custom_endpoints: list[
            Union[RestEndpointBuilder, EndpointRegistrationEntry]
        ] = []

        if global_config.has_pages():
            self.configuration_endpoints.extend(self._gc_schema.configuration_endpoints)
            self.inputs_endpoints.extend(self._gc_schema.inputs_endpoints)
            self.namespace = self._gc_schema.namespace
        self.custom_endpoints.extend(
            global_config.user_defined_handlers.endpoint_registration_entries
        )

        self.configuration_endpoint_names = ", ".join(
            sorted([ep.name for ep in self.configuration_endpoints])
        )
        self.inputs_endpoint_names = ", ".join(
            sorted([ep.name for ep in self.inputs_endpoints])
        )
        self.endpoints.extend(self.configuration_endpoints)
        self.endpoints.extend(self.inputs_endpoints)
        self.endpoints.extend(self.custom_endpoints)

    def generate(self) -> Optional[list[dict[str, str]]]:
        if not self.endpoints:
            return None

        file_path = self.get_file_output_path(["default", self.conf_file])
        self.set_template_and_render(
            template_file_path=["conf_files"], file_name="restmap_conf.template"
        )
        rendered_content = self._template.render(
            endpoints=self.endpoints,
            configuration_endpoints=self.configuration_endpoints,
            inputs_endpoints=self.inputs_endpoints,
            configuration_endpoint_names=self.configuration_endpoint_names,
            inputs_endpoint_names=self.inputs_endpoint_names,
            namespace=self.namespace,
            configuration_capability=self._global_config.capabilities(config=True),
            input_capability=self._global_config.capabilities(inputs=True),
            custom_endpoints=self.custom_endpoints,
        )
        return [
            {
                "file_name": self.conf_file,
                "file_path": file_path,
                "content": rendered_content,
            }
        ]
