from __future__ import annotations

import warnings
from typing import TYPE_CHECKING, Any, Literal, Optional, Union

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

from ._core import (
    DEFAULT_INSTANCE_SPACE,
    DataRecord,
    DataRecordGraphQL,
    DataRecordWrite,
    DomainModel,
    DomainModelCore,
    DomainModelWrite,
    DomainModelWriteList,
    DomainModelList,
    DomainRelationWrite,
    GraphQLCore,
    ResourcesWrite,
)

if TYPE_CHECKING:
    from ._bid_configuration_day_ahead import (
        BidConfigurationDayAhead,
        BidConfigurationDayAheadGraphQL,
        BidConfigurationDayAheadWrite,
    )
    from ._date_specification import DateSpecification, DateSpecificationGraphQL, DateSpecificationWrite
    from ._price_area_day_ahead import PriceAreaDayAhead, PriceAreaDayAheadGraphQL, PriceAreaDayAheadWrite
    from ._shop_model_with_assets import ShopModelWithAssets, ShopModelWithAssetsGraphQL, ShopModelWithAssetsWrite


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


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

_BENCHMARKINGCONFIGURATIONDAYAHEAD_PROPERTIES_BY_FIELD = {
    "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 = 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."""
        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 or DEFAULT_INSTANCE_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 []
            ],
        )

    def as_write(self) -> BenchmarkingConfigurationDayAheadWrite:
        """Convert this GraphQL format of benchmarking configuration day ahead to the writing format."""
        return BenchmarkingConfigurationDayAheadWrite(
            space=self.space or DEFAULT_INSTANCE_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)
    """

    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: Union[list[BidConfigurationDayAhead], list[str], list[dm.NodeId], None] = Field(
        default=None, repr=False, alias="bidConfigurations"
    )
    assets_per_shop_model: Union[list[ShopModelWithAssets], list[str], list[dm.NodeId], None] = 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()


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

    space: str = DEFAULT_INSTANCE_SPACE
    node_type: Union[dm.DirectRelationReference, 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: Union[list[BidConfigurationDayAheadWrite], list[str], list[dm.NodeId], None] = Field(
        default=None, repr=False, alias="bidConfigurations"
    )
    assets_per_shop_model: Union[list[ShopModelWithAssetsWrite], list[str], list[dm.NodeId], None] = Field(
        default=None, repr=False, alias="assetsPerShopModel"
    )

    def _to_instances_write(
        self,
        cache: set[tuple[str, str]],
        view_by_read_class: dict[type[DomainModelCore], dm.ViewId] | None,
        write_none: bool = False,
        allow_version_increase: bool = False,
    ) -> ResourcesWrite:
        resources = ResourcesWrite()
        if self.as_tuple_id() in cache:
            return resources

        write_view = (view_by_read_class or {}).get(
            BenchmarkingConfigurationDayAhead, dm.ViewId("power_ops_core", "BenchmarkingConfigurationDayAhead", "1")
        )

        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=self.node_type,
                sources=[
                    dm.NodeOrEdgeData(
                        source=write_view,
                        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,
                view_by_read_class=view_by_read_class,
                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,
                view_by_read_class=view_by_read_class,
                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, view_by_read_class)
            resources.extend(other_resources)

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

        if isinstance(self.shop_end_specification, DomainModelWrite):
            other_resources = self.shop_end_specification._to_instances_write(cache, view_by_read_class)
            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()


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

    _INSTANCE = BenchmarkingConfigurationDayAheadWrite


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] | list[str] | list[tuple[str, str]] | None = None,
    shop_start_specification: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
    shop_end_specification: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
    external_id_prefix: str | None = None,
    space: str | list[str] | None = None,
    filter: dm.Filter | None = None,
) -> dm.Filter | None:
    filters = []
    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 price_area and isinstance(price_area, str):
        filters.append(
            dm.filters.Equals(
                view_id.as_property_ref("priceArea"), value={"space": DEFAULT_INSTANCE_SPACE, "externalId": price_area}
            )
        )
    if price_area and isinstance(price_area, tuple):
        filters.append(
            dm.filters.Equals(
                view_id.as_property_ref("priceArea"), value={"space": price_area[0], "externalId": price_area[1]}
            )
        )
    if price_area and isinstance(price_area, list) and isinstance(price_area[0], str):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("priceArea"),
                values=[{"space": DEFAULT_INSTANCE_SPACE, "externalId": item} for item in price_area],
            )
        )
    if price_area and isinstance(price_area, list) and isinstance(price_area[0], tuple):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("priceArea"),
                values=[{"space": item[0], "externalId": item[1]} for item in price_area],
            )
        )
    if shop_start_specification and isinstance(shop_start_specification, str):
        filters.append(
            dm.filters.Equals(
                view_id.as_property_ref("shopStartSpecification"),
                value={"space": DEFAULT_INSTANCE_SPACE, "externalId": shop_start_specification},
            )
        )
    if shop_start_specification and isinstance(shop_start_specification, tuple):
        filters.append(
            dm.filters.Equals(
                view_id.as_property_ref("shopStartSpecification"),
                value={"space": shop_start_specification[0], "externalId": shop_start_specification[1]},
            )
        )
    if (
        shop_start_specification
        and isinstance(shop_start_specification, list)
        and isinstance(shop_start_specification[0], str)
    ):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("shopStartSpecification"),
                values=[{"space": DEFAULT_INSTANCE_SPACE, "externalId": item} for item in shop_start_specification],
            )
        )
    if (
        shop_start_specification
        and isinstance(shop_start_specification, list)
        and isinstance(shop_start_specification[0], tuple)
    ):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("shopStartSpecification"),
                values=[{"space": item[0], "externalId": item[1]} for item in shop_start_specification],
            )
        )
    if shop_end_specification and isinstance(shop_end_specification, str):
        filters.append(
            dm.filters.Equals(
                view_id.as_property_ref("shopEndSpecification"),
                value={"space": DEFAULT_INSTANCE_SPACE, "externalId": shop_end_specification},
            )
        )
    if shop_end_specification and isinstance(shop_end_specification, tuple):
        filters.append(
            dm.filters.Equals(
                view_id.as_property_ref("shopEndSpecification"),
                value={"space": shop_end_specification[0], "externalId": shop_end_specification[1]},
            )
        )
    if (
        shop_end_specification
        and isinstance(shop_end_specification, list)
        and isinstance(shop_end_specification[0], str)
    ):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("shopEndSpecification"),
                values=[{"space": DEFAULT_INSTANCE_SPACE, "externalId": item} for item in shop_end_specification],
            )
        )
    if (
        shop_end_specification
        and isinstance(shop_end_specification, list)
        and isinstance(shop_end_specification[0], tuple)
    ):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("shopEndSpecification"),
                values=[{"space": item[0], "externalId": item[1]} 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
