from __future__ import annotations

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

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

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_node_id,
    as_read_args,
    as_write_args,
    is_tuple_id,
    as_instance_dict_id,
    parse_single_connection,
    QueryCore,
    NodeQueryCore,
    StringFilter,
    ViewPropertyId,
    DirectRelationFilter,
)
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

    def as_read(self) -> BenchmarkingConfigurationDayAhead:
        """Convert this GraphQL format of benchmarking configuration day ahead to the reading format."""
        return BenchmarkingConfigurationDayAhead.model_validate(as_read_args(self))

    def as_write(self) -> BenchmarkingConfigurationDayAheadWrite:
        """Convert this GraphQL format of benchmarking configuration day ahead to the writing format."""
        return BenchmarkingConfigurationDayAheadWrite.model_validate(as_write_args(self))


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")
    @field_validator("price_area", "shop_start_specification", "shop_end_specification", mode="before")
    @classmethod
    def parse_single(cls, value: Any, info: ValidationInfo) -> Any:
        return parse_single_connection(value, info.field_name)

    @field_validator("bid_configurations", "assets_per_shop_model", mode="before")
    @classmethod
    def parse_list(cls, value: Any, info: ValidationInfo) -> Any:
        if value is None:
            return None
        return [parse_single_connection(item, info.field_name) for item in value]

    def as_write(self) -> BenchmarkingConfigurationDayAheadWrite:
        """Convert this read version of benchmarking configuration day ahead to the writing version."""
        return BenchmarkingConfigurationDayAheadWrite.model_validate(as_write_args(self))

    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()


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)
    """
    _container_fields: ClassVar[tuple[str, ...]] = ("name", "price_area", "shop_end_specification", "shop_start_specification",)
    _outwards_edges: ClassVar[tuple[tuple[str, dm.DirectRelationReference], ...]] = (("assets_per_shop_model", dm.DirectRelationReference("power_ops_types", "assetsPerShopModel")), ("bid_configurations", dm.DirectRelationReference("power_ops_types", "benchmarkingBidConfigurations")),)
    _direct_relations: ClassVar[tuple[str, ...]] = ("price_area", "shop_end_specification", "shop_start_specification",)

    _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


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_property: ViewPropertyId | 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_property,
            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",
                connection_property=ViewPropertyId(self._view_id, "priceArea"),
            )

        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",
                connection_property=ViewPropertyId(self._view_id, "shopStartSpecification"),
            )

        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",
                connection_property=ViewPropertyId(self._view_id, "shopEndSpecification"),
            )

        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",
                connection_property=ViewPropertyId(self._view_id, "bidConfigurations"),
            )

        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",
                connection_property=ViewPropertyId(self._view_id, "assetsPerShopModel"),
            )

        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.price_area_filter = DirectRelationFilter(self, self._view_id.as_property_ref("priceArea"))
        self.shop_start_specification_filter = DirectRelationFilter(self, self._view_id.as_property_ref("shopStartSpecification"))
        self.shop_end_specification_filter = DirectRelationFilter(self, self._view_id.as_property_ref("shopEndSpecification"))
        self._filter_classes.extend([
            self.space,
            self.external_id,
            self.name,
            self.price_area_filter,
            self.shop_start_specification_filter,
            self.shop_end_specification_filter,
        ])

    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)
