"""CMake configuration generator for variant-specific configuration."""

from pathlib import Path
from typing import Any, Optional

from yanga_core.domain.config import VarsConfig
from yanga_core.domain.config_utils import collect_configs_by_id, parse_config
from yanga_core.domain.execution_context import ExecutionContext

from .cmake_backend import CMakeComment, CMakeElement, CMakeVariable
from .generator import CMakeGenerator


class ConfigCMakeGenerator(CMakeGenerator):
    """Generates CMake configuration file with variant-specific configuration variables."""

    def __init__(self, execution_context: ExecutionContext, output_dir: Path, config: Optional[dict[str, Any]] = None) -> None:
        super().__init__(execution_context, output_dir, config)

    def generate(self) -> list[CMakeElement]:
        """Generate CMake elements for variant configuration."""
        elements: list[CMakeElement] = []
        elements.append(CMakeComment(f"Generated by {self.__class__.__name__}"))

        # Collect all "vars" configs following the priority order: variant → platform → variant-platform
        vars_configs = collect_configs_by_id(self.execution_context, "vars")

        if vars_configs:
            elements.append(CMakeComment("Configuration variables"))
            for config_file in vars_configs:
                vars_config = parse_config(config_file, VarsConfig, self.execution_context.project_root_dir)
                for key, value in vars_config.vars.items():
                    str_value = str(value)
                    # Quote values containing spaces for valid CMake syntax
                    if " " in str_value:
                        str_value = f'"{str_value}"'
                    elements.append(CMakeVariable(key, str_value))

        return elements
