
from typing import Union

import xarray as xr

from tabicl.config.config_benchmark_sweep import ConfigBenchmarkSweep
from tabicl.core.enums import BenchmarkOrigin
from tabicl.results.dataset_manipulations import (add_model_plot_name_as_model_name, average_out_the_cv_split,
                                                  create_normalized_score,
                                                  only_use_models_and_datasets_specified_in_cfg,
                                                  update_model_name_to_model_name_and_enum)
from tabicl.results.normalize_scores import create_normalization_info
from tabicl.results.reformat_results_get import get_reformatted_results


def merge_ds_bench_whytrees_and_sweeps(cfg: ConfigBenchmarkSweep, ds_sweeps: Union[xr.Dataset, list[xr.Dataset]]) -> xr.Dataset:

    assert cfg.benchmark.origin == BenchmarkOrigin.WHYTREES
    if not isinstance(ds_sweeps, list):
        ds_sweeps = [ds_sweeps]
    ds_sweeps = [ds_sweep.copy() for ds_sweep in ds_sweeps]
    
    ds_bench = get_reformatted_results(BenchmarkOrigin.WHYTREES)
    ds_bench = update_model_name_to_model_name_and_enum(ds_bench)
    ds_bench = only_use_models_and_datasets_specified_in_cfg(cfg, ds_bench)

    for i in range(len(ds_sweeps)):
        ds_sweeps[i] = add_model_plot_name_as_model_name(ds_sweeps[i], ds_sweeps[i].attrs['model_plot_name'])

    ds = xr.merge([ds_bench, *ds_sweeps])
    ds = average_out_the_cv_split(ds)
    ds_norm = create_normalization_info(cfg, ds)
    ds['score_min'] = ds_norm['score_min']
    ds['score_max'] = ds_norm['score_max']
    ds = create_normalized_score(ds)

    return ds