from __future__ import annotations

import warnings
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, ClassVar, Literal,  no_type_check, Optional, Union

from cognite.client import data_modeling as dm, CogniteClient
from pydantic import Field
from pydantic import field_validator, model_validator

from cognite.powerops.client._generated.v1.data_classes._core import (
    DEFAULT_INSTANCE_SPACE,
    DEFAULT_QUERY_LIMIT,
    DataRecord,
    DataRecordGraphQL,
    DataRecordWrite,
    DomainModel,
    DomainModelWrite,
    DomainModelWriteList,
    DomainModelList,
    DomainRelation,
    DomainRelationWrite,
    GraphQLCore,
    ResourcesWrite,
    T_DomainModelList,
    as_direct_relation_reference,
    as_instance_dict_id,
    as_node_id,
    as_pygen_node_id,
    are_nodes_equal,
    is_tuple_id,
    select_best_node,
    QueryCore,
    NodeQueryCore,
    StringFilter,

)

if TYPE_CHECKING:
    from cognite.powerops.client._generated.v1.data_classes._bid_configuration_day_ahead import BidConfigurationDayAhead, BidConfigurationDayAheadList, BidConfigurationDayAheadGraphQL, BidConfigurationDayAheadWrite, BidConfigurationDayAheadWriteList
    from cognite.powerops.client._generated.v1.data_classes._date_specification import DateSpecification, DateSpecificationList, DateSpecificationGraphQL, DateSpecificationWrite, DateSpecificationWriteList
    from cognite.powerops.client._generated.v1.data_classes._price_area_day_ahead import PriceAreaDayAhead, PriceAreaDayAheadList, PriceAreaDayAheadGraphQL, PriceAreaDayAheadWrite, PriceAreaDayAheadWriteList
    from cognite.powerops.client._generated.v1.data_classes._shop_model_with_assets import ShopModelWithAssets, ShopModelWithAssetsList, ShopModelWithAssetsGraphQL, ShopModelWithAssetsWrite, ShopModelWithAssetsWriteList


__all__ = [
    "BenchmarkingConfigurationDayAhead",
    "BenchmarkingConfigurationDayAheadWrite",
    "BenchmarkingConfigurationDayAheadApply",
    "BenchmarkingConfigurationDayAheadList",
    "BenchmarkingConfigurationDayAheadWriteList",
    "BenchmarkingConfigurationDayAheadApplyList",
    "BenchmarkingConfigurationDayAheadFields",
    "BenchmarkingConfigurationDayAheadTextFields",
    "BenchmarkingConfigurationDayAheadGraphQL",
]


BenchmarkingConfigurationDayAheadTextFields = Literal["external_id", "name"]
BenchmarkingConfigurationDayAheadFields = Literal["external_id", "name"]

_BENCHMARKINGCONFIGURATIONDAYAHEAD_PROPERTIES_BY_FIELD = {
    "external_id": "externalId",
    "name": "name",
}

class BenchmarkingConfigurationDayAheadGraphQL(GraphQLCore):
    """This represents the reading version of benchmarking configuration day ahead, used
    when data is retrieved from CDF using GraphQL.

    It is used when retrieving data from CDF using GraphQL.

    Args:
        space: The space where the node is located.
        external_id: The external id of the benchmarking configuration day ahead.
        data_record: The data record of the benchmarking configuration day ahead node.
        name: The name of the benchmarking configuration
        price_area: The price area related to the bid calculation task
        shop_start_specification: Relative time spec. for start-time for benchmarking SHOP runs
        shop_end_specification: Relative time spec. for end-time for benchmarking SHOP runs
        bid_configurations: Benchmarking workflow will benchmark (i. e. run SHOP for obligation based on) all BidDocuments generated by these methods
        assets_per_shop_model: The SHOP models to be used for benchmarking of these bid configurations (should be all SHOP models needed to 'cover' the price area)
    """
    view_id: ClassVar[dm.ViewId] = dm.ViewId("power_ops_core", "BenchmarkingConfigurationDayAhead", "1")
    name: Optional[str] = None
    price_area: Optional[PriceAreaDayAheadGraphQL] = Field(default=None, repr=False, alias="priceArea")
    shop_start_specification: Optional[DateSpecificationGraphQL] = Field(default=None, repr=False, alias="shopStartSpecification")
    shop_end_specification: Optional[DateSpecificationGraphQL] = Field(default=None, repr=False, alias="shopEndSpecification")
    bid_configurations: Optional[list[BidConfigurationDayAheadGraphQL]] = Field(default=None, repr=False, alias="bidConfigurations")
    assets_per_shop_model: Optional[list[ShopModelWithAssetsGraphQL]] = Field(default=None, repr=False, alias="assetsPerShopModel")

    @model_validator(mode="before")
    def parse_data_record(cls, values: Any) -> Any:
        if not isinstance(values, dict):
            return values
        if "lastUpdatedTime" in values or "createdTime" in values:
            values["dataRecord"] = DataRecordGraphQL(
                created_time=values.pop("createdTime", None),
                last_updated_time=values.pop("lastUpdatedTime", None),
            )
        return values
    @field_validator("price_area", "shop_start_specification", "shop_end_specification", "bid_configurations", "assets_per_shop_model", mode="before")
    def parse_graphql(cls, value: Any) -> Any:
        if not isinstance(value, dict):
            return value
        if "items" in value:
            return value["items"]
        return value

    # We do the ignore argument type as we let pydantic handle the type checking
    @no_type_check
    def as_read(self) -> BenchmarkingConfigurationDayAhead:
        """Convert this GraphQL format of benchmarking configuration day ahead to the reading format."""
        if self.data_record is None:
            raise ValueError("This object cannot be converted to a read format because it lacks a data record.")
        return BenchmarkingConfigurationDayAhead(
            space=self.space,
            external_id=self.external_id,
            data_record=DataRecord(
                version=0,
                last_updated_time=self.data_record.last_updated_time,
                created_time=self.data_record.created_time,
            ),
            name=self.name,
            price_area=self.price_area.as_read()
if isinstance(self.price_area, GraphQLCore)
else self.price_area,
            shop_start_specification=self.shop_start_specification.as_read()
if isinstance(self.shop_start_specification, GraphQLCore)
else self.shop_start_specification,
            shop_end_specification=self.shop_end_specification.as_read()
if isinstance(self.shop_end_specification, GraphQLCore)
else self.shop_end_specification,
            bid_configurations=[bid_configuration.as_read() for bid_configuration in self.bid_configurations or []],
            assets_per_shop_model=[assets_per_shop_model.as_read() for assets_per_shop_model in self.assets_per_shop_model or []],
        )


    # We do the ignore argument type as we let pydantic handle the type checking
    @no_type_check
    def as_write(self) -> BenchmarkingConfigurationDayAheadWrite:
        """Convert this GraphQL format of benchmarking configuration day ahead to the writing format."""
        return BenchmarkingConfigurationDayAheadWrite(
            space=self.space,
            external_id=self.external_id,
            data_record=DataRecordWrite(existing_version=0),
            name=self.name,
            price_area=self.price_area.as_write()
if isinstance(self.price_area, GraphQLCore)
else self.price_area,
            shop_start_specification=self.shop_start_specification.as_write()
if isinstance(self.shop_start_specification, GraphQLCore)
else self.shop_start_specification,
            shop_end_specification=self.shop_end_specification.as_write()
if isinstance(self.shop_end_specification, GraphQLCore)
else self.shop_end_specification,
            bid_configurations=[bid_configuration.as_write() for bid_configuration in self.bid_configurations or []],
            assets_per_shop_model=[assets_per_shop_model.as_write() for assets_per_shop_model in self.assets_per_shop_model or []],
        )


class BenchmarkingConfigurationDayAhead(DomainModel):
    """This represents the reading version of benchmarking configuration day ahead.

    It is used to when data is retrieved from CDF.

    Args:
        space: The space where the node is located.
        external_id: The external id of the benchmarking configuration day ahead.
        data_record: The data record of the benchmarking configuration day ahead node.
        name: The name of the benchmarking configuration
        price_area: The price area related to the bid calculation task
        shop_start_specification: Relative time spec. for start-time for benchmarking SHOP runs
        shop_end_specification: Relative time spec. for end-time for benchmarking SHOP runs
        bid_configurations: Benchmarking workflow will benchmark (i. e. run SHOP for obligation based on) all BidDocuments generated by these methods
        assets_per_shop_model: The SHOP models to be used for benchmarking of these bid configurations (should be all SHOP models needed to 'cover' the price area)
    """
    _view_id: ClassVar[dm.ViewId] = dm.ViewId("power_ops_core", "BenchmarkingConfigurationDayAhead", "1")

    space: str = DEFAULT_INSTANCE_SPACE
    node_type: Union[dm.DirectRelationReference, None] = dm.DirectRelationReference("power_ops_types", "BenchmarkingConfigurationDayAhead")
    name: str
    price_area: Union[PriceAreaDayAhead, str, dm.NodeId, None] = Field(default=None, repr=False, alias="priceArea")
    shop_start_specification: Union[DateSpecification, str, dm.NodeId, None] = Field(default=None, repr=False, alias="shopStartSpecification")
    shop_end_specification: Union[DateSpecification, str, dm.NodeId, None] = Field(default=None, repr=False, alias="shopEndSpecification")
    bid_configurations: Optional[list[Union[BidConfigurationDayAhead, str, dm.NodeId]]] = Field(default=None, repr=False, alias="bidConfigurations")
    assets_per_shop_model: Optional[list[Union[ShopModelWithAssets, str, dm.NodeId]]] = Field(default=None, repr=False, alias="assetsPerShopModel")

    def as_write(self) -> BenchmarkingConfigurationDayAheadWrite:
        """Convert this read version of benchmarking configuration day ahead to the writing version."""
        return BenchmarkingConfigurationDayAheadWrite(
            space=self.space,
            external_id=self.external_id,
            data_record=DataRecordWrite(existing_version=self.data_record.version),
            name=self.name,
            price_area=self.price_area.as_write()
if isinstance(self.price_area, DomainModel)
else self.price_area,
            shop_start_specification=self.shop_start_specification.as_write()
if isinstance(self.shop_start_specification, DomainModel)
else self.shop_start_specification,
            shop_end_specification=self.shop_end_specification.as_write()
if isinstance(self.shop_end_specification, DomainModel)
else self.shop_end_specification,
            bid_configurations=[bid_configuration.as_write() if isinstance(bid_configuration, DomainModel) else bid_configuration for bid_configuration in self.bid_configurations or []],
            assets_per_shop_model=[assets_per_shop_model.as_write() if isinstance(assets_per_shop_model, DomainModel) else assets_per_shop_model for assets_per_shop_model in self.assets_per_shop_model or []],
        )

    def as_apply(self) -> BenchmarkingConfigurationDayAheadWrite:
        """Convert this read version of benchmarking configuration day ahead to the writing version."""
        warnings.warn(
            "as_apply is deprecated and will be removed in v1.0. Use as_write instead.",
            UserWarning,
            stacklevel=2,
        )
        return self.as_write()

    @classmethod
    def _update_connections(
        cls,
        instances: dict[dm.NodeId | str, BenchmarkingConfigurationDayAhead],  # type: ignore[override]
        nodes_by_id: dict[dm.NodeId | str, DomainModel],
        edges_by_source_node: dict[dm.NodeId, list[dm.Edge | DomainRelation]],
    ) -> None:
        from ._bid_configuration_day_ahead import BidConfigurationDayAhead
        from ._date_specification import DateSpecification
        from ._price_area_day_ahead import PriceAreaDayAhead
        from ._shop_model_with_assets import ShopModelWithAssets

        for instance in instances.values():
            if isinstance(instance.price_area, (dm.NodeId, str)) and (price_area := nodes_by_id.get(instance.price_area)) and isinstance(
                    price_area, PriceAreaDayAhead
            ):
                instance.price_area = price_area
            if isinstance(instance.shop_start_specification, (dm.NodeId, str)) and (shop_start_specification := nodes_by_id.get(instance.shop_start_specification)) and isinstance(
                    shop_start_specification, DateSpecification
            ):
                instance.shop_start_specification = shop_start_specification
            if isinstance(instance.shop_end_specification, (dm.NodeId, str)) and (shop_end_specification := nodes_by_id.get(instance.shop_end_specification)) and isinstance(
                    shop_end_specification, DateSpecification
            ):
                instance.shop_end_specification = shop_end_specification
            if edges := edges_by_source_node.get(instance.as_id()):
                bid_configurations: list[BidConfigurationDayAhead | str | dm.NodeId] = []
                assets_per_shop_model: list[ShopModelWithAssets | str | dm.NodeId] = []
                for edge in edges:
                    value: DomainModel | DomainRelation | str | dm.NodeId
                    if isinstance(edge, DomainRelation):
                        value = edge
                    else:
                        other_end: dm.DirectRelationReference = (
                            edge.end_node
                            if edge.start_node.space == instance.space
                            and edge.start_node.external_id == instance.external_id
                            else edge.start_node
                        )
                        destination: dm.NodeId | str = (
                            as_node_id(other_end)
                            if other_end.space != DEFAULT_INSTANCE_SPACE
                            else other_end.external_id
                        )
                        if destination in nodes_by_id:
                            value = nodes_by_id[destination]
                        else:
                            value = destination
                    edge_type = edge.edge_type if isinstance(edge, DomainRelation) else edge.type

                    if edge_type == dm.DirectRelationReference("power_ops_types", "benchmarkingBidConfigurations") and isinstance(
                        value, (BidConfigurationDayAhead, str, dm.NodeId)
                    ):
                        bid_configurations.append(value)
                    if edge_type == dm.DirectRelationReference("power_ops_types", "assetsPerShopModel") and isinstance(
                        value, (ShopModelWithAssets, str, dm.NodeId)
                    ):
                        assets_per_shop_model.append(value)

                instance.bid_configurations = bid_configurations or None
                instance.assets_per_shop_model = assets_per_shop_model or None




class BenchmarkingConfigurationDayAheadWrite(DomainModelWrite):
    """This represents the writing version of benchmarking configuration day ahead.

    It is used to when data is sent to CDF.

    Args:
        space: The space where the node is located.
        external_id: The external id of the benchmarking configuration day ahead.
        data_record: The data record of the benchmarking configuration day ahead node.
        name: The name of the benchmarking configuration
        price_area: The price area related to the bid calculation task
        shop_start_specification: Relative time spec. for start-time for benchmarking SHOP runs
        shop_end_specification: Relative time spec. for end-time for benchmarking SHOP runs
        bid_configurations: Benchmarking workflow will benchmark (i. e. run SHOP for obligation based on) all BidDocuments generated by these methods
        assets_per_shop_model: The SHOP models to be used for benchmarking of these bid configurations (should be all SHOP models needed to 'cover' the price area)
    """
    _view_id: ClassVar[dm.ViewId] = dm.ViewId("power_ops_core", "BenchmarkingConfigurationDayAhead", "1")

    space: str = DEFAULT_INSTANCE_SPACE
    node_type: Union[dm.DirectRelationReference, dm.NodeId, tuple[str, str], None] = dm.DirectRelationReference("power_ops_types", "BenchmarkingConfigurationDayAhead")
    name: str
    price_area: Union[PriceAreaDayAheadWrite, str, dm.NodeId, None] = Field(default=None, repr=False, alias="priceArea")
    shop_start_specification: Union[DateSpecificationWrite, str, dm.NodeId, None] = Field(default=None, repr=False, alias="shopStartSpecification")
    shop_end_specification: Union[DateSpecificationWrite, str, dm.NodeId, None] = Field(default=None, repr=False, alias="shopEndSpecification")
    bid_configurations: Optional[list[Union[BidConfigurationDayAheadWrite, str, dm.NodeId]]] = Field(default=None, repr=False, alias="bidConfigurations")
    assets_per_shop_model: Optional[list[Union[ShopModelWithAssetsWrite, str, dm.NodeId]]] = Field(default=None, repr=False, alias="assetsPerShopModel")

    @field_validator("price_area", "shop_start_specification", "shop_end_specification", "bid_configurations", "assets_per_shop_model", mode="before")
    def as_node_id(cls, value: Any) -> Any:
        if isinstance(value, dm.DirectRelationReference):
            return dm.NodeId(value.space, value.external_id)
        elif isinstance(value, tuple) and len(value) == 2 and all(isinstance(item, str) for item in value):
            return dm.NodeId(value[0], value[1])
        elif isinstance(value, list):
            return [cls.as_node_id(item) for item in value]
        return value
    def _to_instances_write(
        self,
        cache: set[tuple[str, str]],
        write_none: bool = False,
        allow_version_increase: bool = False,
    ) -> ResourcesWrite:
        resources = ResourcesWrite()
        if self.as_tuple_id() in cache:
            return resources

        properties: dict[str, Any] = {}

        if self.name is not None:
            properties["name"] = self.name

        if self.price_area is not None:
            properties["priceArea"] = {
                "space":  self.space if isinstance(self.price_area, str) else self.price_area.space,
                "externalId": self.price_area if isinstance(self.price_area, str) else self.price_area.external_id,
            }

        if self.shop_start_specification is not None:
            properties["shopStartSpecification"] = {
                "space":  self.space if isinstance(self.shop_start_specification, str) else self.shop_start_specification.space,
                "externalId": self.shop_start_specification if isinstance(self.shop_start_specification, str) else self.shop_start_specification.external_id,
            }

        if self.shop_end_specification is not None:
            properties["shopEndSpecification"] = {
                "space":  self.space if isinstance(self.shop_end_specification, str) else self.shop_end_specification.space,
                "externalId": self.shop_end_specification if isinstance(self.shop_end_specification, str) else self.shop_end_specification.external_id,
            }


        if properties:
            this_node = dm.NodeApply(
                space=self.space,
                external_id=self.external_id,
                existing_version=None if allow_version_increase else self.data_record.existing_version,
                type=as_direct_relation_reference(self.node_type),
                sources=[
                    dm.NodeOrEdgeData(
                        source=self._view_id,
                        properties=properties,
                )],
            )
            resources.nodes.append(this_node)
            cache.add(self.as_tuple_id())



        edge_type = dm.DirectRelationReference("power_ops_types", "benchmarkingBidConfigurations")
        for bid_configuration in self.bid_configurations or []:
            other_resources = DomainRelationWrite.from_edge_to_resources(
                cache,
                start_node=self,
                end_node=bid_configuration,
                edge_type=edge_type,
                write_none=write_none,
                allow_version_increase=allow_version_increase,
            )
            resources.extend(other_resources)

        edge_type = dm.DirectRelationReference("power_ops_types", "assetsPerShopModel")
        for assets_per_shop_model in self.assets_per_shop_model or []:
            other_resources = DomainRelationWrite.from_edge_to_resources(
                cache,
                start_node=self,
                end_node=assets_per_shop_model,
                edge_type=edge_type,
                write_none=write_none,
                allow_version_increase=allow_version_increase,
            )
            resources.extend(other_resources)

        if isinstance(self.price_area, DomainModelWrite):
            other_resources = self.price_area._to_instances_write(cache)
            resources.extend(other_resources)

        if isinstance(self.shop_start_specification, DomainModelWrite):
            other_resources = self.shop_start_specification._to_instances_write(cache)
            resources.extend(other_resources)

        if isinstance(self.shop_end_specification, DomainModelWrite):
            other_resources = self.shop_end_specification._to_instances_write(cache)
            resources.extend(other_resources)

        return resources


class BenchmarkingConfigurationDayAheadApply(BenchmarkingConfigurationDayAheadWrite):
    def __new__(cls, *args, **kwargs) -> BenchmarkingConfigurationDayAheadApply:
        warnings.warn(
            "BenchmarkingConfigurationDayAheadApply is deprecated and will be removed in v1.0. Use BenchmarkingConfigurationDayAheadWrite instead."
            "The motivation for this change is that Write is a more descriptive name for the writing version of the"
            "BenchmarkingConfigurationDayAhead.",
            UserWarning,
            stacklevel=2,
        )
        return super().__new__(cls)


class BenchmarkingConfigurationDayAheadList(DomainModelList[BenchmarkingConfigurationDayAhead]):
    """List of benchmarking configuration day aheads in the read version."""

    _INSTANCE = BenchmarkingConfigurationDayAhead

    def as_write(self) -> BenchmarkingConfigurationDayAheadWriteList:
        """Convert these read versions of benchmarking configuration day ahead to the writing versions."""
        return BenchmarkingConfigurationDayAheadWriteList([node.as_write() for node in self.data])

    def as_apply(self) -> BenchmarkingConfigurationDayAheadWriteList:
        """Convert these read versions of primitive nullable to the writing versions."""
        warnings.warn(
            "as_apply is deprecated and will be removed in v1.0. Use as_write instead.",
            UserWarning,
            stacklevel=2,
        )
        return self.as_write()

    @property
    def price_area(self) -> PriceAreaDayAheadList:
        from ._price_area_day_ahead import PriceAreaDayAhead, PriceAreaDayAheadList

        return PriceAreaDayAheadList([item.price_area for item in self.data if isinstance(item.price_area, PriceAreaDayAhead)])

    @property
    def shop_start_specification(self) -> DateSpecificationList:
        from ._date_specification import DateSpecification, DateSpecificationList

        return DateSpecificationList([item.shop_start_specification for item in self.data if isinstance(item.shop_start_specification, DateSpecification)])

    @property
    def shop_end_specification(self) -> DateSpecificationList:
        from ._date_specification import DateSpecification, DateSpecificationList

        return DateSpecificationList([item.shop_end_specification for item in self.data if isinstance(item.shop_end_specification, DateSpecification)])

    @property
    def bid_configurations(self) -> BidConfigurationDayAheadList:
        from ._bid_configuration_day_ahead import BidConfigurationDayAhead, BidConfigurationDayAheadList

        return BidConfigurationDayAheadList([item for items in self.data for item in items.bid_configurations or [] if isinstance(item, BidConfigurationDayAhead)])

    @property
    def assets_per_shop_model(self) -> ShopModelWithAssetsList:
        from ._shop_model_with_assets import ShopModelWithAssets, ShopModelWithAssetsList

        return ShopModelWithAssetsList([item for items in self.data for item in items.assets_per_shop_model or [] if isinstance(item, ShopModelWithAssets)])


class BenchmarkingConfigurationDayAheadWriteList(DomainModelWriteList[BenchmarkingConfigurationDayAheadWrite]):
    """List of benchmarking configuration day aheads in the writing version."""

    _INSTANCE = BenchmarkingConfigurationDayAheadWrite

    @property
    def price_area(self) -> PriceAreaDayAheadWriteList:
        from ._price_area_day_ahead import PriceAreaDayAheadWrite, PriceAreaDayAheadWriteList

        return PriceAreaDayAheadWriteList([item.price_area for item in self.data if isinstance(item.price_area, PriceAreaDayAheadWrite)])

    @property
    def shop_start_specification(self) -> DateSpecificationWriteList:
        from ._date_specification import DateSpecificationWrite, DateSpecificationWriteList

        return DateSpecificationWriteList([item.shop_start_specification for item in self.data if isinstance(item.shop_start_specification, DateSpecificationWrite)])

    @property
    def shop_end_specification(self) -> DateSpecificationWriteList:
        from ._date_specification import DateSpecificationWrite, DateSpecificationWriteList

        return DateSpecificationWriteList([item.shop_end_specification for item in self.data if isinstance(item.shop_end_specification, DateSpecificationWrite)])

    @property
    def bid_configurations(self) -> BidConfigurationDayAheadWriteList:
        from ._bid_configuration_day_ahead import BidConfigurationDayAheadWrite, BidConfigurationDayAheadWriteList

        return BidConfigurationDayAheadWriteList([item for items in self.data for item in items.bid_configurations or [] if isinstance(item, BidConfigurationDayAheadWrite)])

    @property
    def assets_per_shop_model(self) -> ShopModelWithAssetsWriteList:
        from ._shop_model_with_assets import ShopModelWithAssetsWrite, ShopModelWithAssetsWriteList

        return ShopModelWithAssetsWriteList([item for items in self.data for item in items.assets_per_shop_model or [] if isinstance(item, ShopModelWithAssetsWrite)])

class BenchmarkingConfigurationDayAheadApplyList(BenchmarkingConfigurationDayAheadWriteList): ...



def _create_benchmarking_configuration_day_ahead_filter(
    view_id: dm.ViewId,
    name: str | list[str] | None = None,
    name_prefix: str | None = None,
    price_area: str | tuple[str, str] | dm.NodeId | dm.DirectRelationReference | Sequence[str | tuple[str, str] | dm.NodeId | dm.DirectRelationReference] | None = None,
    shop_start_specification: str | tuple[str, str] | dm.NodeId | dm.DirectRelationReference | Sequence[str | tuple[str, str] | dm.NodeId | dm.DirectRelationReference] | None = None,
    shop_end_specification: str | tuple[str, str] | dm.NodeId | dm.DirectRelationReference | Sequence[str | tuple[str, str] | dm.NodeId | dm.DirectRelationReference] | None = None,
    external_id_prefix: str | None = None,
    space: str | list[str] | None = None,
    filter: dm.Filter | None = None,
) -> dm.Filter | None:
    filters: list[dm.Filter] = []
    if isinstance(name, str):
        filters.append(dm.filters.Equals(view_id.as_property_ref("name"), value=name))
    if name and isinstance(name, list):
        filters.append(dm.filters.In(view_id.as_property_ref("name"), values=name))
    if name_prefix is not None:
        filters.append(dm.filters.Prefix(view_id.as_property_ref("name"), value=name_prefix))
    if isinstance(price_area, str | dm.NodeId | dm.DirectRelationReference) or is_tuple_id(price_area):
        filters.append(dm.filters.Equals(view_id.as_property_ref("priceArea"), value=as_instance_dict_id(price_area)))
    if price_area and isinstance(price_area, Sequence) and not isinstance(price_area, str) and not is_tuple_id(price_area):
        filters.append(dm.filters.In(view_id.as_property_ref("priceArea"), values=[as_instance_dict_id(item) for item in price_area]))
    if isinstance(shop_start_specification, str | dm.NodeId | dm.DirectRelationReference) or is_tuple_id(shop_start_specification):
        filters.append(dm.filters.Equals(view_id.as_property_ref("shopStartSpecification"), value=as_instance_dict_id(shop_start_specification)))
    if shop_start_specification and isinstance(shop_start_specification, Sequence) and not isinstance(shop_start_specification, str) and not is_tuple_id(shop_start_specification):
        filters.append(dm.filters.In(view_id.as_property_ref("shopStartSpecification"), values=[as_instance_dict_id(item) for item in shop_start_specification]))
    if isinstance(shop_end_specification, str | dm.NodeId | dm.DirectRelationReference) or is_tuple_id(shop_end_specification):
        filters.append(dm.filters.Equals(view_id.as_property_ref("shopEndSpecification"), value=as_instance_dict_id(shop_end_specification)))
    if shop_end_specification and isinstance(shop_end_specification, Sequence) and not isinstance(shop_end_specification, str) and not is_tuple_id(shop_end_specification):
        filters.append(dm.filters.In(view_id.as_property_ref("shopEndSpecification"), values=[as_instance_dict_id(item) for item in shop_end_specification]))
    if external_id_prefix is not None:
        filters.append(dm.filters.Prefix(["node", "externalId"], value=external_id_prefix))
    if isinstance(space, str):
        filters.append(dm.filters.Equals(["node", "space"], value=space))
    if space and isinstance(space, list):
        filters.append(dm.filters.In(["node", "space"], values=space))
    if filter:
        filters.append(filter)
    return dm.filters.And(*filters) if filters else None


class _BenchmarkingConfigurationDayAheadQuery(NodeQueryCore[T_DomainModelList, BenchmarkingConfigurationDayAheadList]):
    _view_id = BenchmarkingConfigurationDayAhead._view_id
    _result_cls = BenchmarkingConfigurationDayAhead
    _result_list_cls_end = BenchmarkingConfigurationDayAheadList

    def __init__(
        self,
        created_types: set[type],
        creation_path: list[QueryCore],
        client: CogniteClient,
        result_list_cls: type[T_DomainModelList],
        expression: dm.query.ResultSetExpression | None = None,
        connection_name: str | None = None,
        connection_type: Literal["reverse-list"] | None = None,
        reverse_expression: dm.query.ResultSetExpression | None = None,
    ):
        from ._bid_configuration_day_ahead import _BidConfigurationDayAheadQuery
        from ._date_specification import _DateSpecificationQuery
        from ._price_area_day_ahead import _PriceAreaDayAheadQuery
        from ._shop_model_with_assets import _ShopModelWithAssetsQuery

        super().__init__(
            created_types,
            creation_path,
            client,
            result_list_cls,
            expression,
            dm.filters.HasData(views=[self._view_id]),
            connection_name,
            connection_type,
            reverse_expression,
        )

        if _PriceAreaDayAheadQuery not in created_types:
            self.price_area = _PriceAreaDayAheadQuery(
                created_types.copy(),
                self._creation_path,
                client,
                result_list_cls,
                dm.query.NodeResultSetExpression(
                    through=self._view_id.as_property_ref("priceArea"),
                    direction="outwards",
                ),
                connection_name="price_area",
            )

        if _DateSpecificationQuery not in created_types:
            self.shop_start_specification = _DateSpecificationQuery(
                created_types.copy(),
                self._creation_path,
                client,
                result_list_cls,
                dm.query.NodeResultSetExpression(
                    through=self._view_id.as_property_ref("shopStartSpecification"),
                    direction="outwards",
                ),
                connection_name="shop_start_specification",
            )

        if _DateSpecificationQuery not in created_types:
            self.shop_end_specification = _DateSpecificationQuery(
                created_types.copy(),
                self._creation_path,
                client,
                result_list_cls,
                dm.query.NodeResultSetExpression(
                    through=self._view_id.as_property_ref("shopEndSpecification"),
                    direction="outwards",
                ),
                connection_name="shop_end_specification",
            )

        if _BidConfigurationDayAheadQuery not in created_types:
            self.bid_configurations = _BidConfigurationDayAheadQuery(
                created_types.copy(),
                self._creation_path,
                client,
                result_list_cls,
                dm.query.EdgeResultSetExpression(
                    direction="outwards",
                    chain_to="destination",
                ),
                connection_name="bid_configurations",
            )

        if _ShopModelWithAssetsQuery not in created_types:
            self.assets_per_shop_model = _ShopModelWithAssetsQuery(
                created_types.copy(),
                self._creation_path,
                client,
                result_list_cls,
                dm.query.EdgeResultSetExpression(
                    direction="outwards",
                    chain_to="destination",
                ),
                connection_name="assets_per_shop_model",
            )

        self.space = StringFilter(self, ["node", "space"])
        self.external_id = StringFilter(self, ["node", "externalId"])
        self.name = StringFilter(self, self._view_id.as_property_ref("name"))
        self._filter_classes.extend([
            self.space,
            self.external_id,
            self.name,
        ])

    def list_benchmarking_configuration_day_ahead(self, limit: int = DEFAULT_QUERY_LIMIT) -> BenchmarkingConfigurationDayAheadList:
        return self._list(limit=limit)


class BenchmarkingConfigurationDayAheadQuery(_BenchmarkingConfigurationDayAheadQuery[BenchmarkingConfigurationDayAheadList]):
    def __init__(self, client: CogniteClient):
        super().__init__(set(), [], client, BenchmarkingConfigurationDayAheadList)
