

from dataclasses import is_dataclass
from typing import Any, Optional

from omegaconf import DictConfig, ListConfig, OmegaConf

__all__ = ["omega_conf_to_dataclass"]

def omega_conf_to_dataclass(config: DictConfig | dict, dataclass_type: Optional[type[Any]] = None) -> Any:

    if not config:
        return dataclass_type if dataclass_type is None else dataclass_type()

    if not isinstance(config, DictConfig | ListConfig | dict | list):
        return config

    if dataclass_type is None:
        assert "_target_" in config, (
            "When dataclass_type is not provided, config must contain _target_."
            "See trainer/config/ppo_trainer.yaml algorithm section for an example."
        )
        from hydra.utils import instantiate

        return instantiate(config, _convert_="partial")

    if not is_dataclass(dataclass_type):
        raise ValueError(f"{dataclass_type} must be a dataclass")
    cfg = OmegaConf.create(config)
    cfg_from_dataclass = OmegaConf.structured(dataclass_type)

    cfg_merged = OmegaConf.merge(cfg_from_dataclass, cfg)

    config_object = OmegaConf.to_object(cfg_merged)
    return config_object

def update_dict_with_config(dictionary: dict, config: DictConfig):
    for key in dictionary:
        if hasattr(config, key):
            dictionary[key] = getattr(config, key)
