from __future__ import annotations

from collections.abc import Sequence
from typing import overload

from cognite.client import CogniteClient
from cognite.client import data_modeling as dm
from cognite.client.data_classes.data_modeling.instances import InstanceAggregationResultList

from cognite.powerops.client._generated.data_classes import (
    Scenario,
    ScenarioApply,
    ScenarioApplyList,
    ScenarioFields,
    ScenarioList,
    ScenarioTextFields,
)
from cognite.powerops.client._generated.data_classes._scenario import _SCENARIO_PROPERTIES_BY_FIELD

from ._core import DEFAULT_LIMIT_READ, Aggregations, TypeAPI


class ScenarioAPI(TypeAPI[Scenario, ScenarioApply, ScenarioList]):
    def __init__(self, client: CogniteClient, view_id: dm.ViewId):
        super().__init__(
            client=client,
            sources=view_id,
            class_type=Scenario,
            class_apply_type=ScenarioApply,
            class_list=ScenarioList,
        )
        self._view_id = view_id

    def apply(
        self, scenario: ScenarioApply | Sequence[ScenarioApply], replace: bool = False
    ) -> dm.InstancesApplyResult:
        if isinstance(scenario, ScenarioApply):
            instances = scenario.to_instances_apply()
        else:
            instances = ScenarioApplyList(scenario).to_instances_apply()
        return self._client.data_modeling.instances.apply(
            nodes=instances.nodes,
            edges=instances.edges,
            auto_create_start_nodes=True,
            auto_create_end_nodes=True,
            replace=replace,
        )

    def delete(self, external_id: str | Sequence[str], space="power-ops") -> dm.InstancesDeleteResult:
        if isinstance(external_id, str):
            return self._client.data_modeling.instances.delete(nodes=(space, external_id))
        else:
            return self._client.data_modeling.instances.delete(
                nodes=[(space, id) for id in external_id],
            )

    @overload
    def retrieve(self, external_id: str) -> Scenario:
        ...

    @overload
    def retrieve(self, external_id: Sequence[str]) -> ScenarioList:
        ...

    def retrieve(self, external_id: str | Sequence[str]) -> Scenario | ScenarioList:
        if isinstance(external_id, str):
            return self._retrieve((self._sources.space, external_id))
        else:
            return self._retrieve([(self._sources.space, ext_id) for ext_id in external_id])

    def search(
        self,
        query: str,
        properties: ScenarioTextFields | Sequence[ScenarioTextFields] | None = None,
        name: str | list[str] | None = None,
        name_prefix: str | None = None,
        template: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        mapping: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        commands: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        external_id_prefix: str | None = None,
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,
    ) -> ScenarioList:
        filter_ = _create_filter(
            self._view_id,
            name,
            name_prefix,
            template,
            mapping,
            commands,
            external_id_prefix,
            filter,
        )
        return self._search(self._view_id, query, _SCENARIO_PROPERTIES_BY_FIELD, properties, filter_, limit)

    @overload
    def aggregate(
        self,
        aggregations: Aggregations
        | dm.aggregations.MetricAggregation
        | Sequence[Aggregations]
        | Sequence[dm.aggregations.MetricAggregation],
        property: ScenarioFields | Sequence[ScenarioFields] | None = None,
        group_by: None = None,
        query: str | None = None,
        search_properties: ScenarioTextFields | Sequence[ScenarioTextFields] | None = None,
        name: str | list[str] | None = None,
        name_prefix: str | None = None,
        template: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        mapping: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        commands: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        external_id_prefix: str | None = None,
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,
    ) -> list[dm.aggregations.AggregatedNumberedValue]:
        ...

    @overload
    def aggregate(
        self,
        aggregations: Aggregations
        | dm.aggregations.MetricAggregation
        | Sequence[Aggregations]
        | Sequence[dm.aggregations.MetricAggregation],
        property: ScenarioFields | Sequence[ScenarioFields] | None = None,
        group_by: ScenarioFields | Sequence[ScenarioFields] = None,
        query: str | None = None,
        search_properties: ScenarioTextFields | Sequence[ScenarioTextFields] | None = None,
        name: str | list[str] | None = None,
        name_prefix: str | None = None,
        template: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        mapping: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        commands: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        external_id_prefix: str | None = None,
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,
    ) -> InstanceAggregationResultList:
        ...

    def aggregate(
        self,
        aggregate: Aggregations
        | dm.aggregations.MetricAggregation
        | Sequence[Aggregations]
        | Sequence[dm.aggregations.MetricAggregation],
        property: ScenarioFields | Sequence[ScenarioFields] | None = None,
        group_by: ScenarioFields | Sequence[ScenarioFields] | None = None,
        query: str | None = None,
        search_property: ScenarioTextFields | Sequence[ScenarioTextFields] | None = None,
        name: str | list[str] | None = None,
        name_prefix: str | None = None,
        template: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        mapping: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        commands: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        external_id_prefix: str | None = None,
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,
    ) -> list[dm.aggregations.AggregatedNumberedValue] | InstanceAggregationResultList:
        filter_ = _create_filter(
            self._view_id,
            name,
            name_prefix,
            template,
            mapping,
            commands,
            external_id_prefix,
            filter,
        )
        return self._aggregate(
            self._view_id,
            aggregate,
            _SCENARIO_PROPERTIES_BY_FIELD,
            property,
            group_by,
            query,
            search_property,
            limit,
            filter_,
        )

    def histogram(
        self,
        property: ScenarioFields,
        interval: float,
        query: str | None = None,
        search_property: ScenarioTextFields | Sequence[ScenarioTextFields] | None = None,
        name: str | list[str] | None = None,
        name_prefix: str | None = None,
        template: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        mapping: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        commands: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        external_id_prefix: str | None = None,
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,
    ) -> dm.aggregations.HistogramValue:
        filter_ = _create_filter(
            self._view_id,
            name,
            name_prefix,
            template,
            mapping,
            commands,
            external_id_prefix,
            filter,
        )
        return self._histogram(
            self._view_id,
            property,
            interval,
            _SCENARIO_PROPERTIES_BY_FIELD,
            query,
            search_property,
            limit,
            filter_,
        )

    def list(
        self,
        name: str | list[str] | None = None,
        name_prefix: str | None = None,
        template: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        mapping: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        commands: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
        external_id_prefix: str | None = None,
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,
    ) -> ScenarioList:
        filter_ = _create_filter(
            self._view_id,
            name,
            name_prefix,
            template,
            mapping,
            commands,
            external_id_prefix,
            filter,
        )

        return self._list(limit=limit, filter=filter_)


def _create_filter(
    view_id: dm.ViewId,
    name: str | list[str] | None = None,
    name_prefix: str | None = None,
    template: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
    mapping: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
    commands: str | tuple[str, str] | list[str] | list[tuple[str, str]] | None = None,
    external_id_prefix: str | None = None,
    filter: dm.Filter | None = None,
) -> dm.Filter | None:
    filters = []
    if name and 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:
        filters.append(dm.filters.Prefix(view_id.as_property_ref("name"), value=name_prefix))
    if template and isinstance(template, str):
        filters.append(
            dm.filters.Equals(view_id.as_property_ref("template"), value={"space": "power-ops", "externalId": template})
        )
    if template and isinstance(template, tuple):
        filters.append(
            dm.filters.Equals(
                view_id.as_property_ref("template"), value={"space": template[0], "externalId": template[1]}
            )
        )
    if template and isinstance(template, list) and isinstance(template[0], str):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("template"),
                values=[{"space": "power-ops", "externalId": item} for item in template],
            )
        )
    if template and isinstance(template, list) and isinstance(template[0], tuple):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("template"),
                values=[{"space": item[0], "externalId": item[1]} for item in template],
            )
        )
    if mapping and isinstance(mapping, str):
        filters.append(
            dm.filters.Equals(view_id.as_property_ref("mapping"), value={"space": "power-ops", "externalId": mapping})
        )
    if mapping and isinstance(mapping, tuple):
        filters.append(
            dm.filters.Equals(view_id.as_property_ref("mapping"), value={"space": mapping[0], "externalId": mapping[1]})
        )
    if mapping and isinstance(mapping, list) and isinstance(mapping[0], str):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("mapping"),
                values=[{"space": "power-ops", "externalId": item} for item in mapping],
            )
        )
    if mapping and isinstance(mapping, list) and isinstance(mapping[0], tuple):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("mapping"),
                values=[{"space": item[0], "externalId": item[1]} for item in mapping],
            )
        )
    if commands and isinstance(commands, str):
        filters.append(
            dm.filters.Equals(view_id.as_property_ref("commands"), value={"space": "power-ops", "externalId": commands})
        )
    if commands and isinstance(commands, tuple):
        filters.append(
            dm.filters.Equals(
                view_id.as_property_ref("commands"), value={"space": commands[0], "externalId": commands[1]}
            )
        )
    if commands and isinstance(commands, list) and isinstance(commands[0], str):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("commands"),
                values=[{"space": "power-ops", "externalId": item} for item in commands],
            )
        )
    if commands and isinstance(commands, list) and isinstance(commands[0], tuple):
        filters.append(
            dm.filters.In(
                view_id.as_property_ref("commands"),
                values=[{"space": item[0], "externalId": item[1]} for item in commands],
            )
        )
    if external_id_prefix:
        filters.append(dm.filters.Prefix(["node", "externalId"], value=external_id_prefix))
    if filter:
        filters.append(filter)
    return dm.filters.And(*filters) if filters else None
