"""Platform configuration functionality.

Copyright 2026 Joe Harris / BenchBox Project

Licensed under the MIT License. See LICENSE file in the project root for details.
"""

from __future__ import annotations

import logging
from typing import Any

from benchbox.core.schemas import DatabaseConfig, SystemProfile

logger = logging.getLogger(__name__)


def get_platform_config(
    database_config: DatabaseConfig,
    system_profile: SystemProfile | None,
    benchmark_name: str | None = None,
    scale_factor: float | None = None,
    tuning_config: Any | None = None,
) -> dict[str, Any]:
    """Extract platform-specific configuration from database and system profiles.

    Args:
        database_config: Database configuration object
        system_profile: System profile information (optional)
        benchmark_name: Name of benchmark being run (optional, for config-aware adapters)
        scale_factor: Benchmark scale factor (optional, for config-aware adapters)
        tuning_config: Unified tuning configuration (optional, for config-aware adapters)

    Returns:
        Dictionary of platform configuration parameters
    """
    platform_config = {}

    # Extract ALL fields from DatabaseConfig (including extra fields like server_hostname for Databricks)
    # This uses Pydantic's model_dump() to get both defined and extra fields
    db_config_dict = database_config.model_dump(exclude_none=False)

    # Remove standard DatabaseConfig fields that shouldn't be passed to adapters
    for field in ["type", "name", "connection_string"]:
        db_config_dict.pop(field, None)

    # Start with all database config fields (includes options and any extra platform-specific fields)
    platform_config.update(db_config_dict)

    # Include benchmark context for config-aware adapters (e.g., Databricks, Snowflake)
    # This enables proper schema naming based on benchmark/scale/tuning configuration
    if benchmark_name:
        platform_config["benchmark"] = benchmark_name
    if scale_factor is not None:
        platform_config["scale_factor"] = scale_factor
    if tuning_config is not None:
        platform_config["tuning_config"] = tuning_config
        logger.debug(
            "Tuning configuration passed to platform adapter: %s",
            type(tuning_config).__name__,
        )

    if system_profile:
        total_memory_gb = getattr(system_profile, "memory_total_gb", 4)
        try:
            total_memory_gb_val = float(total_memory_gb)
        except Exception:
            total_memory_gb_val = 4.0

        max_memory_limit = (
            database_config.options.get("max_memory_limit_gb", 16)
            if hasattr(database_config, "options") and database_config.options
            else 16
        )
        platform_config["memory_limit"] = f"{min(int(total_memory_gb_val * 0.8), max_memory_limit)}GB"

        cpu_cores = getattr(system_profile, "cpu_cores_logical", 2)
        try:
            cpu_cores_val = int(cpu_cores)
        except Exception:
            cpu_cores_val = 2
        platform_config["thread_limit"] = min(cpu_cores_val, 8)

    # Note: DuckDB database_path is generated by the adapter's from_config method
    # using proper naming conventions based on benchmark/scale/tuning configuration

    return platform_config
