"""Centralized YAML loader for the TaskRunner project.

Responsibilities:
- Load YAML from a path (default `tasks.yaml`)
- Return RunConfig with YAML + CLI args merged
- Avoid side effects like modifying global state

Design notes:
- Keeps file I/O separate from dataclass constructors for clean architecture
- Handles both YAML defaults and CLI overrides in one place
- Returns ready-to-use RunConfig and task definitions
"""

from __future__ import annotations

from typing import Any
import os
import yaml

from hil_testbench.config.run_config import RunConfig


def load_project_config(
    yaml_path: str = "tasks.yaml",
    cli_args: object | None = None,
) -> tuple[dict[str, Any], RunConfig, dict[str, Any]]:
    """Load project YAML and merge with CLI args to create RunConfig.

    Args:
        yaml_path: Path to YAML config file
        cli_args: Argparse namespace with CLI overrides (optional)

    Returns:
        yaml_data: the raw YAML dictionary (or {})
        run_config: RunConfig with YAML + CLI args merged
        tasks_map: yaml_data.get("tasks", {})
    """
    yaml_data: dict[str, Any] = {}
    if os.path.exists(yaml_path):
        with open(yaml_path, "r", encoding="utf-8") as f:
            yaml_data = yaml.safe_load(f) or {}
        run_config = RunConfig.from_yaml(yaml_data)
    else:
        run_config = RunConfig()

    # Apply CLI overrides if provided
    if cli_args is not None:
        run_config.max_log_size_main_mb = getattr(
            cli_args, "max_log_size_main", run_config.max_log_size_main_mb
        )
        run_config.max_log_file_count_main = getattr(
            cli_args, "max_log_file_count_main", run_config.max_log_file_count_main
        )
        run_config.enable_runner_health = not getattr(
            cli_args, "disable_health", not run_config.enable_runner_health
        )
        run_config.runner_health_interval = getattr(
            cli_args, "health_interval", run_config.runner_health_interval
        )

    tasks_map = yaml_data.get("tasks", {})
    return yaml_data, run_config, tasks_map
