# ======================================================================================
#
#     Rapid Deep Neural Networks
#
#     Licensed under the MIT License
# ______________________________________________________________________________________
# ......................................................................................

# Copyright (c) 2018-2026 Pantelis I. Kaplanoglou

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# .......................................................................................
from typing import Dict, Type, Any

from radnn.errors import *
from .data_hyperparams import DataHyperparams
from radnn import mlsys



# ======================================================================================================================
class RadnnDataset(type):
  def __new__(mcls, name: str, bases: tuple[type, ...], ns: dict[str, Any]):
    cls = super().__new__(mcls, name, bases, ns)
    # Avoid registering the abstract base itself
    if name != "DatasetBuildAdapter":
      key = ns.get("NAME", name)  # optional override via class attribute NAME
      if key in DatasetFactory.registry:
        raise KeyError(f"The dataset '{key}' has been already registered ")
      DatasetFactory.registry[key] = cls
      
      alt_keys = cls.name_alias()
      for alt_key in alt_keys:
        alt_key = alt_key + "BuildAdapter"
        if alt_key in DatasetFactory.registry:
          raise KeyError(f"The dataset '{alt_key}' has been already registered ")
        DatasetFactory.registry[alt_key] = cls
        
    return cls
# ======================================================================================================================



# ======================================================================================================================
class DatasetBuildAdapter(metaclass=RadnnDataset):
  # --------------------------------------------------------------------------------------------------------------------
  @classmethod
  def name_alias(self):
    return []
  # --------------------------------------------------------------------------------------------------------------------
  def __init__(self, **kwargs):
    self.builder_kwargs = kwargs
    self.hprm: dict | None = self.builder_kwargs.get("hprm", None)
    self.hyperparams: DataHyperparams | None = self.builder_kwargs.get("model_hyperparams", None)
    if self.hyperparams is not None:
      self.hprm = self.hyperparams.hprm
    
    self.fs = self.builder_kwargs.get("dataset_fs", None)
    self.dataset = None
  # --------------------------------------------------------------------------------------------------------------------
  def build(self, **kwargs: Any):
    raise NotImplementedError
  # --------------------------------------------------------------------------------------------------------------------
# ======================================================================================================================







# ======================================================================================================================
class DatasetFactory(object):
  registry: Dict[str, Type["ModelBuildAdapter"]] = {}
  
  @classmethod
  def produce(cls, hyperparams: dict, **kwargs: Any) -> DatasetBuildAdapter:
    oDataset, oDatasetBuilder = None, None
    oDatasetHyperparams: DataHyperparams = DataHyperparams.from_dict(hyperparams)
    assert oDatasetHyperparams.sample_dims is not None, HPARAMS_DATA_SAMPLE_DIMS
    assert len(oDatasetHyperparams.sample_dims) > 0, HPARAMS_DATA_SAMPLE_DIMS
    
    sModelAdapterKey = oDatasetHyperparams.dataset_name + "BuildAdapter"
    if sModelAdapterKey in cls.registry:
      oDatasetFS = mlsys.filesys.datasets.subfs(oDatasetHyperparams.dataset_fs_name)
      
      cBuilder: DatasetBuildAdapter = DatasetFactory.registry[sModelAdapterKey]
      oDatasetBuilder = cBuilder(model_hyperparams=oDatasetHyperparams, dataset_fs=oDatasetFS, **kwargs)
      oDataset = oDatasetBuilder.build(hprm=hyperparams, **kwargs)
    
    if oDataset is None:
      raise Exception(MODEL_BUILDER_NOT_REGISTERED % oDatasetHyperparams.base_name)
    
    return oDatasetBuilder
# ======================================================================================================================
