"""
This file contains a minimal set of tests for compliance with the extension
array interface test suite, and should contain no other tests.
The test suite for the full functionality of the array is located in
`pandas/tests/arrays/`.

The tests in this file are inherited from the BaseExtensionTests, and only
minimal tweaks should be applied to get the tests passing (by overwriting a
parent method).

Additional tests should either be added to one of the BaseExtensionTests
classes (if they are relevant for the extension interface for all dtypes), or
be added to the array-specific tests in `pandas/tests/arrays/`.

"""

import numpy as np
import pytest

from pandas.core.dtypes.dtypes import DatetimeTZDtype

import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import DatetimeArray
from pandas.tests.extension import base


@pytest.fixture
def dtype():
    return DatetimeTZDtype(unit="ns", tz="US/Central")


@pytest.fixture
def data(dtype):
    data = DatetimeArray._from_sequence(
        pd.date_range("2000", periods=10, tz=dtype.tz), dtype=dtype
    )
    return data


@pytest.fixture
def data_missing(dtype):
    return DatetimeArray._from_sequence(
        np.array(["NaT", "2000-01-01"], dtype="datetime64[ns]"), dtype=dtype
    )


@pytest.fixture
def data_for_sorting(dtype):
    a = pd.Timestamp("2000-01-01")
    b = pd.Timestamp("2000-01-02")
    c = pd.Timestamp("2000-01-03")
    return DatetimeArray._from_sequence(
        np.array([b, c, a], dtype="datetime64[ns]"), dtype=dtype
    )


@pytest.fixture
def data_missing_for_sorting(dtype):
    a = pd.Timestamp("2000-01-01")
    b = pd.Timestamp("2000-01-02")
    return DatetimeArray._from_sequence(
        np.array([b, "NaT", a], dtype="datetime64[ns]"), dtype=dtype
    )


@pytest.fixture
def data_for_grouping(dtype):
    """
    Expected to be like [B, B, NA, NA, A, A, B, C]

    Where A < B < C and NA is missing
    """
    a = pd.Timestamp("2000-01-01")
    b = pd.Timestamp("2000-01-02")
    c = pd.Timestamp("2000-01-03")
    na = "NaT"
    return DatetimeArray._from_sequence(
        np.array([b, b, na, na, a, a, b, c], dtype="datetime64[ns]"), dtype=dtype
    )


@pytest.fixture
def na_cmp():
    def cmp(a, b):
        return a is pd.NaT and a is b

    return cmp


# ----------------------------------------------------------------------------
class TestDatetimeArray(base.ExtensionTests):
    def _get_expected_exception(self, op_name, obj, other):
        if op_name in ["__sub__", "__rsub__"]:
            return None
        return super()._get_expected_exception(op_name, obj, other)

    def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool):
        if op_name == "std":
            return "timedelta64[ns]"
        return arr.dtype

    def _supports_accumulation(self, ser, op_name: str) -> bool:
        return op_name in ["cummin", "cummax"]

    def _supports_reduction(self, obj, op_name: str) -> bool:
        return op_name in ["min", "max", "median", "mean", "std", "count"]

    def test_series_constructor(self, data):
        # Series construction drops any .freq attr
        data = data.view()
        data._freq = None
        super().test_series_constructor(data)

    @pytest.mark.parametrize("na_action", [None, "ignore"])
    def test_map(self, data, na_action):
        result = data.map(lambda x: x, na_action=na_action)
        tm.assert_extension_array_equal(result, data)

    @pytest.mark.skip("DatetimeArray.round uses a different signature (freq).")
    def test_round(self, data):
        pass

    def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool):
        if op_name in ["median", "mean", "std"]:
            alt = ser.astype("int64")

            res_op = getattr(ser, op_name)
            exp_op = getattr(alt, op_name)
            result = res_op(skipna=skipna)
            expected = exp_op(skipna=skipna)
            if op_name in ["mean", "median"]:
                # error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype"
                # has no attribute "tz"
                tz = ser.dtype.tz  # type: ignore[union-attr]
                expected = pd.Timestamp(expected, tz=tz)
            else:
                expected = pd.Timedelta(expected)
            tm.assert_almost_equal(result, expected)

        else:
            return super().check_reduce(ser, op_name, skipna)

    @pytest.mark.filterwarnings(
        "ignore:The default formatting of datetime/timedelta values:DeprecationWarning"
    )
    def test_values_for_json(self, data):
        # GH 65127
        # DatetimeArray relies on the default 'epoch' format for datetimes, leading to
        # the filtered Pandas4Warning.
        super().test_values_for_json(data)

    @pytest.mark.filterwarnings(
        "ignore:The default formatting of datetime/timedelta values:DeprecationWarning"
    )
    @pytest.mark.xfail(
        raises=AssertionError, reason="DatetimeArray does not support JSON roundtrip."
    )
    def test_json_roundtrip(self, data):
        # GH 65127
        # DatetimeArray fails on roundtrip. Also currently the json serialization relies
        # on the default 'epoch' format for datetimes, leading to the filtered
        # Pandas4Warning.
        super().test_json_roundtrip(data)

    @pytest.mark.xfail(raises=AssertionError, reason="numpy array are different")
    def test_plot_on_x_axis(self, plot_data):
        # GH 64535, GH 65915
        # A tz-aware DatetimeArray on the x-axis is converted to a PeriodArray and
        # thereby loses its tz information. Therefore the check that the plotted data
        # is matching the expected converted data fails.
        super().test_plot_on_x_axis(plot_data)


class Test2DCompat(base.NDArrayBacked2DTests):
    pass
