from __future__ import annotations

from typing import Any, Mapping, TypeVar

from pyimgano.workbench.config_parse_primitives import _optional_int, _require_mapping
from pyimgano.workbench.config_section_parsers import (
    _parse_adaptation_config,
    _parse_dataset_config,
    _parse_defects_config,
    _parse_model_config,
    _parse_output_config,
    _parse_prediction_config,
    _parse_preprocessing_config,
    _parse_training_config,
)
from pyimgano.workbench.config_types import WorkbenchConfig

WorkbenchConfigT = TypeVar("WorkbenchConfigT", bound=WorkbenchConfig)


def build_workbench_config_from_dict(
    raw: Mapping[str, Any],
    *,
    config_cls: type[WorkbenchConfigT] = WorkbenchConfig,
) -> WorkbenchConfigT:
    top = _require_mapping(raw, name="config")

    recipe = str(top.get("recipe", "industrial-adapt"))
    seed = _optional_int(top.get("seed", None), name="seed")

    return config_cls(
        dataset=_parse_dataset_config(top, seed=seed),
        model=_parse_model_config(top),
        recipe=recipe,
        seed=seed,
        output=_parse_output_config(top),
        adaptation=_parse_adaptation_config(top),
        preprocessing=_parse_preprocessing_config(top),
        training=_parse_training_config(top),
        defects=_parse_defects_config(top),
        prediction=_parse_prediction_config(top),
    )


__all__ = ["build_workbench_config_from_dict"]
