# LICENSE HEADER MANAGED BY add-license-header
#
# Copyright 2018 Kornia Team
#
# 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.
#

from typing import Any, Dict, Optional, Tuple

import torch

from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
from kornia.augmentation.base import _mixed_gate_shape_error
from kornia.augmentation.utils import _transform_output_shape
from kornia.constants import Resample
from kornia.core.utils import _torch_inverse_cast
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints


class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
    r"""Build a 2D coordinate transform, applied per sample with probability ``p`` (default 0.5).

    ``output = MyAugmentation(...)(input)`` warps images of shape ``(B, C, H, W)`` once a subclass implements
    ``compute_transformation`` and ``apply_transform``. Implement ``inverse_transform`` to support image inversion.
    Use :class:`IntensityAugmentationBase2D` for an augmentation that changes values without moving coordinates.

    See the Convention block on :class:`~kornia.augmentation.AugmentationBase2D`.

    Args:
        p: probability for applying an augmentation. This param controls the augmentation probabilities
          element-wise for a batch.
        p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
          probabilities batch-wise.
        same_on_batch: apply the same transformation across the batch.
        keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
          to the batch form ``False``.

    Convention:
        - pixel coordinates are ``(x, y)`` at integer pixel centers, with corners ``(0, 0)`` and
          ``(W - 1, H - 1)`` (see :doc:`/get-started/conventions`); rotations, shears and affine maps are centered
          at ``((W - 1) / 2, (H - 1) / 2)``, and ``transform_matrix`` maps input pixel coordinates to output pixel
          coordinates.
        - the resampling classes, including the non-rigid :class:`RandomElasticTransform` and
          :class:`RandomThinPlateSpline`, default to bilinear interpolation with zero sampler padding. The
          ``align_corners`` default is ``True`` for :class:`RandomRotation`, :class:`RandomRotation90` and the crop
          and resize classes, and ``False`` for :class:`RandomAffine`, :class:`RandomShear`,
          :class:`RandomTranslate`, :class:`RandomPerspective`, :class:`RandomElasticTransform` and
          :class:`RandomThinPlateSpline` (`#4412 <https://github.com/kornia/kornia/issues/4412>`_).
        - this base provides a matrix-based ``inverse`` interface. Whether a concrete augmentation can invert a
          call depends on its implementation: a subclass without ``inverse_transform`` raises ``NotImplementedError``.
          Inverse resampling cannot recover image or mask information lost through cropping, padding, or
          interpolation. Tensor-form boxes may lose rotated corners through axis-aligned enclosure.
          For an empty batch, image and mask inverse restore the spatial dimensions recorded in the parameters.
        - containers process integer masks in at least float32 and reject labels that cannot be represented
          exactly in the working dtype. Direct ``transform_masks`` calls use the image dtype guard and therefore
          reject ``bool`` masks.
        - a subclass supplies its own :meth:`inverse_transform` -- the base raises ``NotImplementedError`` --
          while :meth:`compute_inverse_transformation` defaults to inverting the sampled matrix.
        - a scalar magnitude ``x`` means ``center ± x``, as it does for the intensity classes: its lower end
          is floored at the parameter's lower bound, and an upper end past the upper bound raises the same
          error the explicit range does. The bounds are ``(-360, 360)`` for :class:`RandomRotation`'s and
          :class:`RandomAffine`'s ``degrees`` and for :class:`RandomShear`'s and :class:`RandomAffine`'s
          ``shear``, ``(-1, 1)`` for :class:`RandomTranslate`'s ``translate_x`` and ``translate_y``,
          ``(0, 1)`` for :class:`RandomAffine`'s ``translate``, and ``(-3, 3)`` for
          :class:`RandomRotation90`'s ``times``. The 3D angle ranges -- :class:`RandomRotation3D`'s and
          :class:`RandomAffine3D`'s ``degrees``, :class:`RandomAffine3D`'s ``shears`` and
          :class:`RandomMotionBlur3D`'s ``angle`` -- raise ``ValueError`` past ``(-360, 360)``, in scalar and
          explicit form.

    Note:
        Masks are resampled with nearest neighbour whatever ``resample`` the augmentation uses for images,
        unless ``resample`` is passed explicitly to ``transform_masks()`` or ``inverse_masks()`` --
        which is what ``extra_args[DataKey.MASK]`` does in a container. An explicit value is honoured in
        both directions. Antialiasing is disabled for masks by default, even when it is enabled for images.
        Only :class:`Resize` and its subclasses, :class:`LongestMaxSize` and :class:`SmallestMaxSize`, read the
        flag: pass ``antialias=True`` explicitly to ``transform_masks()`` or through ``extra_args[DataKey.MASK]`` to
        filter soft masks. Other geometric augmentations ignore it.

    See Also:
        - :class:`AugmentationBase2D`: base class for general 2D augmentations.

    """

    def inverse_transform(
        self,
        input: torch.Tensor,
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
        size: Optional[Tuple[int, int]] = None,
    ) -> torch.Tensor:
        """By default, the exact transformation as ``apply_transform`` will be used."""
        raise NotImplementedError

    def compute_inverse_transformation(self, transform: torch.Tensor) -> torch.Tensor:
        """Compute the inverse transform of given transformation matrices."""
        return _torch_inverse_cast(transform)

    def get_transformation_matrix(
        self,
        input: torch.Tensor,
        params: Optional[Dict[str, torch.Tensor]] = None,
        flags: Optional[Dict[str, Any]] = None,
    ) -> torch.Tensor:
        """Obtain transformation matrices.

        Return the current transformation matrix if existed. Generate a new one, otherwise.
        """
        flags = self.flags if flags is None else flags
        if params is not None:
            transform = self.generate_transformation_matrix(input, params, flags)
        elif self.transform_matrix is None:
            params = self.forward_parameters(input.shape)
            transform = self.generate_transformation_matrix(input, params, flags)
        else:
            transform = self.transform_matrix
        return torch.as_tensor(transform, device=input.device, dtype=input.dtype)

    def apply_non_transform_mask(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        """Process masks corresponding to the inputs that are no transformation applied."""
        return input

    def transform_masks(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
        **kwargs: Any,
    ) -> torch.Tensor:
        # Nearest is the mask default, but an explicit ``resample`` wins, matching ``inverse_masks``.
        if "resample" not in kwargs and "resample" in (self.flags if flags is None else flags):
            kwargs["resample"] = Resample.get("nearest")

        # Disable antialiasing by default for masks so discrete labels are preserved,
        # while allowing an explicit override for soft masks.
        if "antialias" not in kwargs and "antialias" in (self.flags if flags is None else flags):
            kwargs["antialias"] = False

        return super().transform_masks(input, params, flags, transform=transform, **kwargs)

    def apply_transform_mask(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        """Process masks corresponding to the inputs that are transformed.

        Note:
            Uses ``flags["resample"]`` as given; ``transform_masks()`` supplies "nearest" when the caller
            did not choose one.
            Treats ``align_corners=None`` as the module's own ``align_corners``, so a mask is resampled on the
            same grid as its input.

        """
        align_corners_was_none: bool = False
        original_align_corners: Optional[bool] = None

        # When align_corners=None is in flags (from extra_args), use the module's default, so masks use the
        # same align_corners as inputs. This holds in 'slice' cropping_mode too: RandomResizedCrop drops
        # align_corners for nearest itself (#4852), and RandomCrop's slice resize does not read it.
        if "align_corners" in flags and flags["align_corners"] is None:
            align_corners_was_none = True
            original_align_corners = None
            flags["align_corners"] = self.flags.get("align_corners", False)

        output = self.apply_transform(input, params, flags, transform)

        # Restore align_corners if it was modified
        if align_corners_was_none:
            flags["align_corners"] = original_align_corners

        return output

    def apply_transform_box(
        self,
        input: Boxes,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> Boxes:
        """Process boxes corresponding to the inputs that are transformed."""
        if transform is None:
            if self.transform_matrix is None:
                raise RuntimeError("No valid transformation matrix found. Please either pass one or forward one first.")
            transform = self.transform_matrix
        input = self.apply_non_transform_box(input, params, flags, transform)
        return input.transform_boxes_(transform)

    def apply_transform_keypoint(
        self,
        input: Keypoints,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> Keypoints:
        """Process keypoints corresponding to the inputs that are transformed."""
        if transform is None:
            if self.transform_matrix is None:
                raise RuntimeError("No valid transformation matrix found. Please either pass one or forward one first.")
            transform = self.transform_matrix
        input = self.apply_non_transform_keypoint(input, params, flags, transform)
        return input.transform_keypoints_(transform)

    def apply_transform_class(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        """Process class tags corresponding to the inputs that are transformed."""
        return input

    def inverse_inputs(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
        **kwargs: Any,
    ) -> torch.Tensor:
        """Inverse image inputs.

        For an empty batch with recorded input-shape metadata, image and mask inverses
        restore the recorded spatial size while preserving the inverse input's channel count.
        """
        in_tensor = self.transform_tensor(input)
        output = in_tensor.clone()
        to_apply = self._gate(params)

        params, flags = self._process_kwargs_to_params_and_flags(
            self._params if params is None else params, flags, **kwargs
        )

        size: Optional[Tuple[int, int]] = None
        if "forward_input_shape" in params:
            # Majorly for cropping functions
            _size = params["forward_input_shape"].tolist()
            size = (_size[-2], _size[-1])

        # An empty batch has no applied rows, but still needs its recorded spatial shape restored.
        if in_tensor.shape[0] == 0 and size is not None:
            output = in_tensor.reshape(*in_tensor.shape[:-2], *size)
        # if no augmentation needed
        elif not to_apply.any():
            output = in_tensor
        # if all data needs to be augmented
        elif to_apply.all():
            output = self.inverse_transform(in_tensor, flags=flags, transform=transform, size=size)
        else:
            if size is not None and tuple(in_tensor.shape[-2:]) != size:
                raise _mixed_gate_shape_error(in_tensor.shape[1:], (*in_tensor.shape[1:-2], *size), inverse=True)
            output[to_apply] = self.inverse_transform(
                in_tensor[to_apply],
                transform=transform[to_apply] if transform is not None else transform,
                size=size,
                flags=flags,
            )
        return output

    def inverse_masks(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
        **kwargs: Any,
    ) -> torch.Tensor:
        # Mask-specific overrides must not change the caller's flags, even if inverse_inputs raises.
        flags = dict(flags)
        if "resample" in flags:
            flags["resample"] = Resample.get("nearest")
        # Preserve align_corners from extra_args (kwargs) if provided
        # This ensures masks use the same align_corners setting in inverse as in forward
        if "align_corners" in kwargs:
            # When align_corners=None is in kwargs, use the module's default, as apply_transform_mask does.
            # We need to normalize it in kwargs too, because inverse_inputs will call
            # _process_kwargs_to_params_and_flags which merges kwargs into flags
            if kwargs["align_corners"] is None:
                normalized_align_corners = self.flags.get("align_corners", False)
                flags["align_corners"] = normalized_align_corners
                # Also update kwargs to prevent _process_kwargs_to_params_and_flags from overwriting
                kwargs["align_corners"] = normalized_align_corners
            else:
                flags["align_corners"] = kwargs["align_corners"]
        # Interpret mask batches as in transform_masks, rather than treating every 3-D mask as CHW.
        shape = params.get("forward_input_shape")
        in_tensor = self.transform_tensor(input, shape=shape, match_channel=False)
        output = self.inverse_inputs(in_tensor, params, flags, transform, **kwargs)
        return _transform_output_shape(output, input.shape, reference_shape=shape) if self.keepdim else output

    def inverse_boxes(
        self,
        input: Boxes,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
        **kwargs: Any,
    ) -> Boxes:
        output = input.clone()
        to_apply = self._gate(params)

        if transform is None:
            raise RuntimeError("`transform` has to be a torch.Tensor. Got None.")

        params, flags = self._process_kwargs_to_params_and_flags(
            self._params if params is None else params, flags, **kwargs
        )

        # if no augmentation needed
        if not to_apply.any():
            output = input
        # if all data needs to be augmented
        elif to_apply.all():
            output = input.transform_boxes_(transform)
        else:
            # Indexing with `to_apply` would select whole videos on the batch axis of a
            # :class:`VideoBoxes`, while the gate has one entry per frame. Blend on the flat
            # storage instead, as :meth:`transform_boxes` does, so a partial gate applies the
            # inverse to exactly the frames that were augmented.
            applied = input.clone().transform_boxes_(transform)
            output = input.clone()
            output._data = self._blend_by_prob(applied.data, input.data, to_apply)
            output._valid = self._blend_by_prob(applied._valid, input._valid, to_apply)

        return output

    def inverse_keypoints(
        self,
        input: Keypoints,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
        **kwargs: Any,
    ) -> Keypoints:
        """Inverse the transformation on keypoints.

        Args:
            input: input keypoints torch.Tensor or object.
            params: the corresponding parameters for an operation.
            flags: static parameters.
            transform: the inverse transformation matrix
            kwargs: additional arguments

        """
        output = input.clone()
        to_apply = self._gate(params)

        if transform is None:
            raise RuntimeError("`transform` has to be a torch.Tensor. Got None.")

        params, flags = self._process_kwargs_to_params_and_flags(
            self._params if params is None else params, flags, **kwargs
        )

        # if no augmentation needed
        if not to_apply.any():
            output = input
        # if all data needs to be augmented
        elif to_apply.all():
            output = input.transform_keypoints_(transform)
        else:
            output[to_apply] = input[to_apply].transform_keypoints_(transform[to_apply])

        return output

    def inverse_classes(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
        **kwargs: Any,
    ) -> torch.Tensor:
        return input

    def inverse(
        self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None, **kwargs: Any
    ) -> torch.Tensor:
        """Perform inverse operations.

        Args:
            input: the input torch.Tensor.
            params: the corresponding parameters for an operation.
                If None, a new parameter suite will be generated.
            **kwargs: key-value pairs to override the parameters and flags.

        """
        input_shape = input.shape
        in_tensor = self.transform_tensor(input)

        params, flags = self._process_kwargs_to_params_and_flags(
            self._params if params is None else params, self.flags, **kwargs
        )

        if params is None:
            params = self._params
        transform = self.get_transformation_matrix(in_tensor, params=params, flags=flags)

        transform = self.compute_inverse_transformation(transform)
        output = self.inverse_inputs(in_tensor, params, flags, transform)

        if self.keepdim:
            return self.transform_output_tensor(output, input_shape)

        return output
