from __future__ import annotations
{% if data_class.has_primitive_field_of_type((dm.Timestamp, dm.Date)) %}
import datetime{% endif %}
from collections.abc import Sequence
from typing import overload
import warnings

from cognite.client import CogniteClient
from cognite.client import data_modeling as dm{% if data_class.has_field_of_type(ft.PrimitiveFieldCore) %}
from cognite.client.data_classes.data_modeling.instances import InstanceAggregationResultList{% endif %}

from {{ top_level_package }}.data_classes._core import DEFAULT_INSTANCE_SPACE
from {{ top_level_package }}.data_classes import (
    DomainModelCore,
    DomainModelApply,
    ResourcesApplyResult,
    {{ data_class.read_name }},{% if data_class.is_writable %}
    {{ data_class.write_name }},{% endif %}{% if data_class.has_field_of_type(ft.PrimitiveFieldCore) %}
    {{ data_class.field_names }},{% endif %}
    {{ data_class.read_list_name }},{% if data_class.is_writable %}
    {{ data_class.write_list_name }},{% endif %}{% if data_class.has_primitive_field_of_type(dm.Text) %}
    {{ data_class.text_field_names }},{% endif %}{% for edge_data_class in edge_data_classes %}
    {{ edge_data_class.read_name }},
    {{ edge_data_class.write_name }},
    {{ edge_data_class.read_list_name }},{% endfor %}
)
from {{ top_level_package }}.data_classes.{{ data_class.file_name }} import ({% if not data_class.has_only_one_to_many_edges and data_class.has_field_of_type(ft.PrimitiveFieldCore) %}
    {{ data_class.properties_dict_name }},{%  endif %}
    {{ data_class.filter_name }},
)
from ._core import DEFAULT_LIMIT_READ, DEFAULT_QUERY_LIMIT, Aggregations, {% if data_class.is_writable %}NodeAPI{% else %}NodeReadAPI{% endif %}, SequenceNotStr, QueryStep, QueryBuilder{% for class_ in edge_apis %}
from .{{ class_.file_name }} import {{ class_.name }}{% endfor %}{% for class_ in timeseries_apis %}
from .{{ class_.file_name }} import {{ class_.name }}{% endfor %}
from .{{ query_api.file_name }} import {{ query_api.name }}


class {{ api_class.name }}({% if data_class.is_writable %}NodeAPI{% else %}NodeReadAPI{% endif %}[{{ data_class.read_name }}{% if data_class.is_writable %}, {{ data_class.write_name }}{% endif %}, {{ data_class.read_list_name }}]):
    def __init__(self, client: CogniteClient, view_by_read_class: dict[type[DomainModelCore], dm.ViewId]):
        view_id = view_by_read_class[{{ data_class.read_name }}]
        super().__init__(
            client=client,
            sources={% if data_class.is_all_fields_of_type(ft.EdgeOneToMany) %}None{% else %}view_id{% endif %},
            class_type={{ data_class.read_name }},
            class_list={{ data_class.read_list_name }},{% if data_class.is_writable %}
            class_apply_list={{ data_class.write_list_name }},{% endif %}
            view_by_read_class=view_by_read_class,
        )
        self._view_id = view_id{% for edge_api in edge_apis %}
        self.{{ edge_api.parent_attribute }} = {{ edge_api.name }}(
            client{% if edge_api.has_edge_class %}, view_by_read_class, {{ edge_api.edge_class.read_name }}, {{ edge_api.edge_class.write_name }}, {{ edge_api.edge_class.read_list_name }}{% endif %}
        ){% endfor %}{% for timeseries_api in timeseries_apis %}
        self.{{ timeseries_api.parent_attribute }} = {{ timeseries_api.name }}(client, view_id){% endfor %}

    def __call__(
            self,{% for parm in list_method.parameters %}
            {{ parm.name }}: {{ parm.annotation }} = {{ parm.default }},{% endfor %}
            limit: int = DEFAULT_QUERY_LIMIT,
            filter: dm.Filter | None = None,
    ) -> {{ query_api.name }}[{{ data_class.read_list_name }}]:
        """Query starting at {{ data_class.doc_list_name }}.

        Args:{% for parm in list_method.parameters %}
            {{ parm.name }}: {{ parm.description }}{% endfor %}
            limit: Maximum number of {{ data_class.doc_list_name }} to return. Defaults to 25. Set to -1, float("inf") or None to return all items.
            filter: (Advanced) If the filtering available in the above is not sufficient, you can write your own filtering which will be ANDed with the filter above.

        Returns:
            A query API for {{ data_class.doc_list_name}}.

        """
        has_data = dm.filters.HasData(views=[self._view_id])
        filter_ = {{ data_class.filter_name }}(
            self._view_id,{% for parm in list_method.parameters %}
            {{ parm.name }},{% endfor %}
            (filter and dm.filters.And(filter, has_data)) or has_data,
        )
        builder = QueryBuilder({{ data_class.read_list_name }})
        return {{ query_api.name }}(self._client, builder, self._view_by_read_class, filter_, limit)

{% if data_class.is_writable %}
    def apply(
        self,
        {{ data_class.variable }}: {{ data_class.write_name }} | Sequence[{{ data_class.write_name }}],
        replace: bool = False,
        write_none: bool = False,
    ) -> ResourcesApplyResult:
        """Add or update (upsert) {{data_class.doc_list_name}}.{% if data_class.has_field_of_type(ft.EdgeOneToMany) %}

        Note: This method iterates through all nodes and timeseries linked to {{ data_class.variable }} and creates them including the edges
        between the nodes. For example, if any of {{ data_class.one_to_many_edges_docs }} are set, then these
        nodes as well as any nodes linked to them, and all the edges linking these nodes will be created.{% endif %}

        Args:
            {{ data_class.variable }}: {{ data_class.doc_name.capitalize() }} or sequence of {{ data_class.doc_list_name }} to upsert.
            replace (bool): How do we behave when a property value exists? Do we replace all matching and existing values with the supplied values (true)?
                Or should we merge in new values for properties together with the existing values (false)? Note: This setting applies for all nodes or edges specified in the ingestion call.
            write_none (bool): This method, will by default, skip properties that are set to None. However, if you want to set properties to None,
                you can set this parameter to True. Note this only applies to properties that are nullable.
        Returns:
            Created instance(s), i.e., nodes, edges, and time series.

        Examples:

            Create a new {{ data_class.variable }}:

                >>> from {{ top_level_package }} import {{ client_name }}
                >>> from {{ top_level_package }}.data_classes import {{ data_class.write_name }}
                >>> client = {{ client_name }}()
                >>> {{ data_class.variable }} = {{ data_class.write_name }}(external_id="my_{{ data_class.variable }}", ...)
                >>> result = client.{{ api_class.parent_attribute }}.apply({{ data_class.variable }})

        """
        warnings.warn(
            "The .apply method is deprecated and will be removed in v1.0. "
            "Please use the .apply method on the client instead. This means instead of "
            "`my_client.{{ api_class.parent_attribute }}.apply(my_items)` please use `my_client.apply(my_items)`."
            "The motivation is that all apply methods are the same, and having one apply method per API "
            " class encourages users to create items in small batches, which is inefficient.",
            UserWarning,
            stacklevel=2,
        )
        return self._apply({{ data_class.variable }}, replace, write_none)
{% endif %}
    def delete(self, external_id: str | SequenceNotStr[str], space: str = DEFAULT_INSTANCE_SPACE) -> dm.InstancesDeleteResult:
        """Delete one or more {{ data_class.doc_name }}.

        Args:
            external_id: External id of the {{ data_class.doc_name }} to delete.
            space: The space where all the {{ data_class.doc_name }} are located.

        Returns:
            The instance(s), i.e., nodes and edges which has been deleted. Empty list if nothing was deleted.

        Examples:

            Delete {{ data_class.variable }} by id:

                >>> from {{ top_level_package }} import {{ client_name }}
                >>> client = {{ client_name }}()
                >>> client.{{ api_class.parent_attribute }}.delete("my_{{ data_class.variable }}")
        """
        return self._delete(external_id, space)

    @overload
    def retrieve(self, external_id: str, space: str = DEFAULT_INSTANCE_SPACE) -> {{ data_class.read_name }} | None:
        ...

    @overload
    def retrieve(self, external_id: SequenceNotStr[str], space: str = DEFAULT_INSTANCE_SPACE) -> {{ data_class.read_list_name }}:
        ...

    def retrieve(self, external_id: str | SequenceNotStr[str], space: str = DEFAULT_INSTANCE_SPACE) -> {{ data_class.read_name }} | {{ data_class.read_list_name }} | None:
        """Retrieve one or more {{data_class.doc_list_name}} by id(s).

        Args:
            external_id: External id or list of external ids of the {{ data_class.doc_list_name }}.
            space: The space where all the {{ data_class.doc_list_name }} are located.

        Returns:
            The requested {{ data_class.doc_list_name }}.

        Examples:

            Retrieve {{ data_class.variable }} by id:

                >>> from {{ top_level_package }} import {{ client_name }}
                >>> client = {{ client_name }}()
                >>> {{ data_class.variable }} = client.{{ api_class.parent_attribute }}.retrieve("my_{{ data_class.variable }}")

        """{% if data_class.has_field_of_type(ft.EdgeOneToMany) %}
        return self._retrieve(
            external_id,
            space,
            retrieve_edges=True,
            edge_api_name_type_direction_quad=[{% for edge_api in edge_apis %}
                (
                    self.{{ edge_api.parent_attribute }},
                    "{{ edge_api.field_name }}",
                    dm.DirectRelationReference("{{ edge_api.type.space }}", "{{ edge_api.type.external_id }}"),
                    "{{ edge_api.direction }}",
                ),{% endfor %}
                                               ]
        )
        {% else %}
        return self._retrieve(external_id, space){% endif %}
{% if data_class.has_primitive_field_of_type(dm.Text) %}
    def search(
        self,
        query: str,
        properties: {{ data_class.text_field_names }} | Sequence[{{ data_class.text_field_names }}] | None = None,{% for parm in list_method.parameters %}
        {{ parm.name }}: {{ parm.annotation }} = {{ parm.default }},{% endfor %}
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,
    ) -> {{ data_class.read_list_name }}:
        """Search {{ data_class.doc_list_name }}

        Args:
            query: The search query,
            properties: The property to search, if nothing is passed all text fields will be searched.{% for parm in list_method.parameters %}
            {{ parm.name }}: {{ parm.description }}{% endfor %}
            limit: Maximum number of {{ data_class.doc_list_name }} to return. Defaults to 25. Set to -1, float("inf") or None to return all items.
            filter: (Advanced) If the filtering available in the above is not sufficient, you can write your own filtering which will be ANDed with the filter above.

        Returns:
            Search results {{ data_class.doc_list_name}} matching the query.

        Examples:

           Search for 'my_{{ data_class.variable }}' in all text properties:

                >>> from {{ top_level_package }} import {{ client_name }}
                >>> client = {{ client_name }}()
                >>> {{ data_class.variable_list }} = client.{{ api_class.parent_attribute }}.search('my_{{ data_class.variable }}')

        """
        filter_ = {{ data_class.filter_name }}(
            self._view_id,{% for parm in list_method.parameters %}
            {{ parm.name }},{% endfor %}
            filter,
        )
        return self._search(self._view_id, query, {{ data_class.properties_dict_name }}, properties, filter_, limit){% endif %}
{% if data_class.has_field_of_type(ft.PrimitiveFieldCore) %}
    @overload
    def aggregate(
        self,
        aggregations: Aggregations
        | dm.aggregations.MetricAggregation
        | Sequence[Aggregations]
        | Sequence[dm.aggregations.MetricAggregation],
        property: {{ data_class.field_names }} | Sequence[{{ data_class.field_names }}] | None = None,
        group_by: None = None,{% if data_class.has_primitive_field_of_type(dm.Text) %}
        query: str | None = None,
        search_properties: {{ data_class.text_field_names }} | Sequence[{{ data_class.text_field_names }}] | None = None,{% endif %}{% for parm in list_method.parameters %}
        {{ parm.name }}: {{ parm.annotation }} = {{ parm.default }},{% endfor %}
        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: {{ data_class.field_names }} | Sequence[{{ data_class.field_names }}] | None = None,
        group_by: {{ data_class.field_names }} | Sequence[{{ data_class.field_names }}] = None,{% if data_class.has_primitive_field_of_type(dm.Text) %}
        query: str | None = None,
        search_properties: {{ data_class.text_field_names }} | Sequence[{{ data_class.text_field_names }}] | None = None,{% endif %}{% for parm in list_method.parameters %}
        {{ parm.name }}: {{ parm.annotation }} = {{ parm.default }},{% endfor %}
        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: {{ data_class.field_names }} | Sequence[{{ data_class.field_names }}] | None = None,
        group_by: {{ data_class.field_names }} | Sequence[{{ data_class.field_names }}] | None = None,{% if data_class.has_primitive_field_of_type(dm.Text) %}
        query: str | None = None,
        search_property: {{ data_class.text_field_names }} | Sequence[{{ data_class.text_field_names }}] | None = None,{% endif %}{% for parm in list_method.parameters %}
        {{ parm.name }}: {{ parm.annotation }} = {{ parm.default }},{% endfor %}
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,
    ) -> list[dm.aggregations.AggregatedNumberedValue] | InstanceAggregationResultList:
        """Aggregate data across {{ data_class.doc_list_name }}

        Args:
            aggregate: The aggregation to perform.
            property: The property to perform aggregation on.
            group_by: The property to group by when doing the aggregation.{% if data_class.has_primitive_field_of_type(dm.Text) %}
            query: The query to search for in the text field.
            search_property: The text field to search in.{% endif %}{% for parm in list_method.parameters %}
            {{ parm.name }}: {{ parm.description }}{% endfor %}
            limit: Maximum number of {{ data_class.doc_list_name }} to return. Defaults to 25. Set to -1, float("inf") or None to return all items.
            filter: (Advanced) If the filtering available in the above is not sufficient, you can write your own filtering which will be ANDed with the filter above.

        Returns:
            Aggregation results.

        Examples:

            Count {{ data_class.doc_list_name }} in space `my_space`:

                >>> from {{ top_level_package }} import {{ client_name }}
                >>> client = {{ client_name }}()
                >>> result = client.{{ api_class.parent_attribute }}.aggregate("count", space="my_space")

        """

        filter_ = {{ data_class.filter_name }}(
            self._view_id,{% for parm in list_method.parameters %}
            {{ parm.name }},{% endfor %}
            filter,
        )
        return self._aggregate(
            self._view_id,
            aggregate,
            {{ data_class.properties_dict_name }},
            property,
            group_by,{% if data_class.has_primitive_field_of_type(dm.Text) %}
            query,
            search_property,{% else %}
            None,
            None,{% endif %}
            limit,
            filter_,
        )

    def histogram(
        self,
        property: {{ data_class.field_names }},
        interval: float,{% if data_class.has_primitive_field_of_type(dm.Text) %}
        query: str | None = None,
        search_property: {{ data_class.text_field_names }} | Sequence[{{ data_class.text_field_names }}] | None = None,{% endif %}{% for parm in list_method.parameters %}
        {{ parm.name }}: {{ parm.annotation }} = {{ parm.default }},{% endfor %}
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,
    ) -> dm.aggregations.HistogramValue:
        """Produces histograms for {{ data_class.doc_list_name }}

        Args:
            property: The property to use as the value in the histogram.
            interval: The interval to use for the histogram bins.{% if data_class.has_primitive_field_of_type(dm.Text) %}
            query: The query to search for in the text field.
            search_property: The text field to search in.{% endif %}{% for parm in list_method.parameters %}
            {{ parm.name }}: {{ parm.description }}{% endfor %}
            limit: Maximum number of {{ data_class.doc_list_name }} to return. Defaults to 25. Set to -1, float("inf") or None to return all items.
            filter: (Advanced) If the filtering available in the above is not sufficient, you can write your own filtering which will be ANDed with the filter above.

        Returns:
            Bucketed histogram results.

        """
        filter_ = {{ data_class.filter_name }}(
            self._view_id,{% for parm in list_method.parameters %}
            {{ parm.name }},{% endfor %}
            filter,
        )
        return self._histogram(
            self._view_id,
            property,
            interval,
            {{ data_class.properties_dict_name }},{% if data_class.has_primitive_field_of_type(dm.Text) %}
            query,
            search_property,{% else %}
            None,
            None,{% endif %}
            limit,
            filter_,
        )
{% endif %}

    def list(
        self,{% for parm in list_method.parameters %}
        {{ parm.name }}: {{ parm.annotation }} = {{ parm.default }},{% endfor %}
        limit: int = DEFAULT_LIMIT_READ,
        filter: dm.Filter | None = None,{% if data_class.has_field_of_type(ft.EdgeOneToMany) %}
        retrieve_edges: bool = True,{% endif %}
    ) -> {{ data_class.read_list_name }}:
        """List/filter {{ data_class.doc_list_name }}

        Args:{% for parm in list_method.parameters %}
            {{ parm.name }}: {{ parm.description }}{% endfor %}
            limit: Maximum number of {{ data_class.doc_list_name }} to return. Defaults to 25. Set to -1, float("inf") or None to return all items.
            filter: (Advanced) If the filtering available in the above is not sufficient, you can write your own filtering which will be ANDed with the filter above. {% if data_class.has_field_of_type(ft.EdgeOneToMany) %}
            retrieve_edges: Whether to retrieve {{ data_class.one_to_many_edges_docs }} external ids for the {{ data_class.doc_list_name }}. Defaults to True.{% endif %}

        Returns:
            List of requested {{ data_class.doc_list_name}}

        Examples:

            List {{ data_class.doc_list_name }} and limit to 5:

                >>> from {{ top_level_package }} import {{ client_name }}
                >>> client = {{ client_name }}()
                >>> {{ data_class.variable_list }} = client.{{ api_class.parent_attribute }}.list(limit=5)

        """
        filter_ = {{ data_class.filter_name }}(
            self._view_id,{% for parm in list_method.parameters %}
            {{ parm.name }},{% endfor %}
            filter,
        )
        {% if data_class.has_field_of_type(ft.EdgeOneToMany) %}
        return self._list(
            limit=limit,
            filter=filter_,
            retrieve_edges=retrieve_edges,
            edge_api_name_type_direction_quad=[{% for edge_api in edge_apis %}
                (
                    self.{{ edge_api.parent_attribute }},
                    "{{ edge_api.field_name }}",
                    dm.DirectRelationReference("{{ edge_api.type.space }}", "{{ edge_api.type.external_id }}"),
                    "{{ edge_api.direction }}",
                ),{% endfor %}
                                               ]
        )
        {% else %}return self._list(limit=limit, filter=filter_){% endif %}
