import keras
import numpy as np

from keras_aug._src.layers.composition.random_choice import RandomChoice
from keras_aug._src.layers.vision.identity import Identity
from keras_aug._src.layers.vision.random_grayscale import RandomGrayscale
from keras_aug._src.layers.vision.resize import Resize
from keras_aug._src.testing.test_case import TestCase
from keras_aug._src.utils.test_utils import get_images


class RandomChoiceTest(TestCase):
    def test_correctness(self):
        import torch
        import torchvision.transforms.v2.functional as TF
        from keras.src.backend.torch import convert_to_tensor

        layer = RandomChoice(
            transforms=[RandomGrayscale(p=1.0), Identity()], p=[1.0, 0.0]
        )

        x = get_images("float32", "channels_last")
        y = layer(x)

        ref_y = TF.rgb_to_grayscale(
            convert_to_tensor(np.transpose(x, [0, 3, 1, 2])),
            num_output_channels=3,
        )
        ref_y = torch.permute(ref_y, (0, 2, 3, 1))
        self.assertAllClose(y, ref_y)

        # Test p=0.0
        layer = RandomChoice(
            transforms=[RandomGrayscale(p=1.0), Identity()], p=[0.0, 1.0]
        )
        y = layer(x)

        self.assertAllClose(y, x)

    def test_shape(self):
        layer = RandomChoice(transforms=[RandomGrayscale(p=1.0), Identity()])

        # Test dynamic shape
        x = keras.KerasTensor((None, None, None, 3))
        y = layer(x)
        self.assertEqual(y.shape, (None, None, None, 3))

        # Test static shape
        x = keras.KerasTensor((None, 32, 32, 3))
        y = layer(x)
        self.assertEqual(y.shape, (None, 32, 32, 3))

        # Test deterministic shape
        layer = RandomChoice(transforms=[Resize((16, 16)), Resize((16, 16))])
        x = keras.KerasTensor((None, 16, 16, 3))
        y = layer(x)
        self.assertEqual(y.shape, (None, 16, 16, 3))

    def test_model(self):
        layer = RandomChoice(transforms=[RandomGrayscale(p=1.0), Identity()])
        inputs = keras.layers.Input(shape=[None, None, 3])
        outputs = layer(inputs)
        model = keras.models.Model(inputs, outputs)
        self.assertEqual(model.output_shape, (None, None, None, 3))

    def test_config(self):
        x = get_images("float32", "channels_last")
        layer = RandomChoice(
            transforms=[RandomGrayscale(p=1.0), Identity()], p=[1.0, 0.0]
        )
        y = layer(x)

        layer = RandomChoice.from_config(layer.get_config())
        y2 = layer(x)
        self.assertAllClose(y, y2)

    def test_tf_data_compatibility(self):
        import tensorflow as tf

        layer = RandomChoice(
            transforms=[RandomGrayscale(p=1.0), RandomGrayscale(p=1.0)]
        )
        x = get_images("float32", "channels_last")
        ds = tf.data.Dataset.from_tensor_slices(x).batch(2).map(layer)
        for output in ds.take(1):
            self.assertIsInstance(output, tf.Tensor)
            self.assertEqual(output.shape, (2, 32, 32, 3))
