# Copyright 2026 the HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import (
    ImageProcessingTester,
    ImageProcessingTestMixin,
    load_coco_image,
    prepare_image_inputs,
    prepare_video_inputs,
)


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image


class Kimi26ImageProcessingTester(ImageProcessingTester):
    def __init__(self, **kwargs):
        # Random test inputs kwargs
        kwargs.setdefault("num_frames", 10)
        kwargs.setdefault("min_resolution", 56)
        kwargs.setdefault("max_resolution", 1024)

        # Image processor init kwargs
        kwargs.setdefault("size", {"max_height": 512, "max_width": 512})
        kwargs.setdefault("max_patches", 36)

        super().__init__(**kwargs)

    def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
        images = prepare_image_inputs(
            batch_size=self.batch_size,
            num_channels=self.num_channels,
            min_resolution=self.min_resolution,
            max_resolution=self.max_resolution,
            equal_resolution=equal_resolution,
            numpify=numpify,
            torchify=torchify,
        )
        return [[image] for image in images]

    def prepare_video_inputs(self, equal_resolution=False, numpify=False, torchify=False):
        return prepare_video_inputs(
            batch_size=self.batch_size,
            num_channels=self.num_channels,
            num_frames=self.num_frames,
            min_resolution=self.min_resolution,
            max_resolution=self.max_resolution,
            equal_resolution=equal_resolution,
            numpify=numpify,
            torchify=torchify,
        )


@require_torch
@require_vision
class Kimi26ImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
    image_processor_tester_class = Kimi26ImageProcessingTester

    def test_call_pil(self):
        for image_processing_class in self.image_processing_classes.values():
            # Initialize image_processing
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random PIL images
            image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True)
            for image in image_inputs:
                self.assertIsInstance(image[0], Image.Image)

            # Test not batched input
            process_out = image_processing(image_inputs[0], return_tensors="pt")
            encoded_images = process_out.pixel_values
            image_grid_thws = process_out.image_grid_thw
            expected_output_image_shape = (36, 3, 14, 14)
            expected_image_grid_thws = torch.Tensor([[1, 6, 6]])
            self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
            self.assertTrue((image_grid_thws == expected_image_grid_thws).all())

            # Test batched
            process_out = image_processing(image_inputs, return_tensors="pt")
            encoded_images = process_out.pixel_values
            image_grid_thws = process_out.image_grid_thw
            expected_output_image_shape = (252, 3, 14, 14)
            expected_image_grid_thws = torch.Tensor([[1, 6, 6]] * self.image_processor_tester.batch_size)
            self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
            self.assertTrue((image_grid_thws == expected_image_grid_thws).all())

    def test_call_numpy(self):
        for image_processing_class in self.image_processing_classes.values():
            # Initialize image_processing
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random numpy tensors
            image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, numpify=True)
            for image in image_inputs:
                self.assertIsInstance(image[0], np.ndarray)

            # Test not batched input
            process_out = image_processing(image_inputs[0], return_tensors="pt")
            encoded_images = process_out.pixel_values
            image_grid_thws = process_out.image_grid_thw
            expected_output_image_shape = (36, 3, 14, 14)
            expected_image_grid_thws = torch.Tensor([[1, 6, 6]])
            self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
            self.assertTrue((image_grid_thws == expected_image_grid_thws).all())

            # Test batched
            process_out = image_processing(image_inputs, return_tensors="pt")
            encoded_images = process_out.pixel_values
            image_grid_thws = process_out.image_grid_thw
            expected_output_image_shape = (252, 3, 14, 14)
            expected_image_grid_thws = torch.Tensor([[1, 6, 6]] * self.image_processor_tester.batch_size)
            self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
            self.assertTrue((image_grid_thws == expected_image_grid_thws).all())

    def test_call_pytorch(self):
        for image_processing_class in self.image_processing_classes.values():
            # Initialize image_processing
            image_processing = image_processing_class(**self.image_processor_dict)
            # create random PyTorch tensors
            image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True)

            for image in image_inputs:
                self.assertIsInstance(image[0], torch.Tensor)

            # Test not batched input
            process_out = image_processing(image_inputs[0], return_tensors="pt")
            encoded_images = process_out.pixel_values
            image_grid_thws = process_out.image_grid_thw
            expected_output_image_shape = (36, 3, 14, 14)
            expected_image_grid_thws = torch.Tensor([[1, 6, 6]])
            self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
            self.assertTrue((image_grid_thws == expected_image_grid_thws).all())

            # Test batched
            process_out = image_processing(image_inputs, return_tensors="pt")
            encoded_images = process_out.pixel_values
            image_grid_thws = process_out.image_grid_thw
            expected_output_image_shape = (252, 3, 14, 14)
            expected_image_grid_thws = torch.Tensor([[1, 6, 6]] * self.image_processor_tester.batch_size)
            self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
            self.assertTrue((image_grid_thws == expected_image_grid_thws).all())

    @unittest.skip(reason="Kimi26ImageProcessor doesn't treat 4 channel PIL and numpy consistently yet")
    def test_call_numpy_4_channels(self):
        pass

    def test_nested_input(self):
        for image_processing_class in self.image_processing_classes.values():
            image_processing = image_processing_class(**self.image_processor_dict)
            image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True)

            # Test batched as a list of images
            process_out = image_processing(image_inputs, return_tensors="pt")
            encoded_images = process_out.pixel_values
            image_grid_thws = process_out.image_grid_thw
            expected_output_image_shape = (252, 3, 14, 14)
            expected_image_grid_thws = torch.Tensor([[1, 6, 6]] * self.image_processor_tester.batch_size)
            self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
            self.assertTrue((image_grid_thws == expected_image_grid_thws).all())

            # Test batched as a nested list of images, where each sublist is one batch
            image_inputs_nested = image_inputs[:3] + image_inputs[3:]
            process_out = image_processing(image_inputs_nested, return_tensors="pt")
            encoded_images_nested = process_out.pixel_values
            image_grid_thws_nested = process_out.image_grid_thw
            expected_output_image_shape = (252, 3, 14, 14)
            expected_image_grid_thws = torch.Tensor([[1, 6, 6]] * self.image_processor_tester.batch_size)
            self.assertEqual(tuple(encoded_images_nested.shape), expected_output_image_shape)
            self.assertTrue((image_grid_thws == expected_image_grid_thws).all())

            # Image processor should return same pixel values, independently of ipnut format
            self.assertTrue((encoded_images_nested == encoded_images).all())
            self.assertTrue((image_grid_thws_nested == expected_image_grid_thws).all())

    def test_non_square_grid_orientation(self):
        # Regression test: `navit_resize` used to be called with transposed (height, width) arguments, distorting
        # every non-square image. The grid must be [1, height // patch, width // patch] after padding.
        for image_processing_class in self.image_processing_classes.values():
            image_processor_dict = {**self.image_processor_dict, "max_patches": 16384}
            image_processing = image_processing_class(**image_processor_dict)
            image = Image.fromarray(np.random.default_rng(0).integers(0, 256, (56, 112, 3), dtype=np.uint8))
            process_out = image_processing(image, return_tensors="pt")
            self.assertEqual(process_out.image_grid_thw.tolist(), [[1, 4, 8]])

            # A landscape image and its portrait transpose must produce transposed grids
            portrait = Image.fromarray(np.asarray(image).transpose(1, 0, 2))
            process_out = image_processing(portrait, return_tensors="pt")
            self.assertEqual(process_out.image_grid_thw.tolist(), [[1, 8, 4]])

    def test_custom_pixels(self):
        "Test different values for min and max pixels when resizing"
        pixel_choices = frozenset((100, 150, 200, 20000))
        for image_processing_class in self.image_processing_classes.values():
            image_processor_dict = self.image_processor_dict.copy()
            for size in pixel_choices:
                image_processor_dict["size"] = {"max_height": size, "max_width": size}
                image_processor = image_processing_class(**image_processor_dict)
                image_inputs = self.image_processor_tester.prepare_image_inputs()
                # Just checking that it doesn't raise an error
                image_processor(image_inputs, return_tensors="pt")

        # Can't assign different sizes for H and W
        with self.assertRaises(ValueError):
            image_processor_dict = self.image_processor_dict.copy()
            image_processor_dict["size"] = {"max_height": 100, "max_width": 200}
            image_processor = image_processing_class(**image_processor_dict)
            image_inputs = self.image_processor_tester.prepare_image_inputs()
            image_processor(image_inputs, return_tensors="pt")

    # Override to test additional outputs for equivalence such as `image_grid_thw`
    def test_backends_equivalence(self):
        dummy_image = load_coco_image("000000039769.jpg")

        # Create processors for each backend
        encodings = {}
        for backend_name, image_processing_class in self.image_processing_classes.items():
            image_processor = image_processing_class(**self.image_processor_dict)
            encodings[backend_name] = image_processor(dummy_image, return_tensors="pt")

        # Compare all backends to the first one (reference backend)
        backend_names = list(encodings.keys())
        reference_backend = backend_names[0]
        reference_encoding = encodings[reference_backend]
        for backend_name in backend_names[1:]:
            self._assert_tensors_equivalence(reference_encoding.pixel_values, encodings[backend_name].pixel_values)
            self.assertEqual(reference_encoding.image_grid_thw.dtype, encodings[backend_name].image_grid_thw.dtype)
            self._assert_tensors_equivalence(
                reference_encoding.image_grid_thw.float(), encodings[backend_name].image_grid_thw.float()
            )

    def test_backends_equivalence_batched(self):
        if hasattr(self.image_processor_tester, "do_center_crop") and self.image_processor_tester.do_center_crop:
            self.skipTest(
                reason="Skipping as do_center_crop is True and center_crop functions are not equivalent for fast and slow processors"
            )

        dummy_images = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)

        # Create processors for each backend
        encodings = {}
        for backend_name, image_processing_class in self.image_processing_classes.items():
            image_processor = image_processing_class(**self.image_processor_dict)
            encodings[backend_name] = image_processor(dummy_images, return_tensors="pt")

        # Compare all backends to the first one (reference backend)
        backend_names = list(encodings.keys())
        reference_backend = backend_names[0]
        reference_encoding = encodings[reference_backend]
        for backend_name in backend_names[1:]:
            self._assert_tensors_equivalence(reference_encoding.pixel_values, encodings[backend_name].pixel_values)
            self.assertEqual(reference_encoding.image_grid_thw.dtype, encodings[backend_name].image_grid_thw.dtype)
            self._assert_tensors_equivalence(
                reference_encoding.image_grid_thw.float(), encodings[backend_name].image_grid_thw.float()
            )
