# 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 __future__ import annotations

from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, TypeVar, Union

import torch
from torch import float16, float32, float64

from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype
from kornia.augmentation.utils.helpers import _IMAGE_SHAPES, _raise_input_rank_error
from kornia.core.ops import eye_like
from kornia.core.utils import _to_device_nonblocking, is_autocast_enabled, is_compiling, is_exporting
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints

_F = TypeVar("_F", bound=Callable[..., torch.Tensor])


def _input_metadata_only(method: _F) -> _F:
    """Mark an implementation that only reads the input's shape, dtype and device.

    Store the function itself, not a boolean: an override (including a wrapper that
    copies function attributes) must not inherit another implementation's promise.
    Overridable callees in the matrix path are checked separately.
    """
    method.__dict__["_kornia_input_metadata_only"] = method
    return method


class _InputMetadata(NamedTuple):
    shape: Tuple[int, ...]
    dtype: torch.dtype
    device: torch.device

    def materialize(self) -> torch.Tensor:
        # These implementations never read pixels. Allocate one element only when
        # the matrix is requested, preserving the original shape without its storage.
        return torch.empty((), dtype=self.dtype, device=self.device).expand(self.shape)


_LazyMatrixArgs = Tuple[Union[torch.Tensor, _InputMetadata], Dict[str, torch.Tensor], Dict[str, Any]]


class AugmentationBase2D(_AugmentationBase):
    r"""Build a custom 2D augmentation, applied per sample with probability ``p`` (default 0.5).

    ``output = MyAugmentation(...)(input)`` processes images of shape ``(B, C, H, W)`` once a subclass
    implements ``apply_transform`` and supplies any parameter generation it needs. This generic base supports
    custom operations, including matrix-free warps such as :class:`RandomElasticTransform` and
    :class:`RandomThinPlateSpline`. Use :class:`IntensityAugmentationBase2D` for value-only operations or
    :class:`GeometricAugmentationBase2D` for matrix-based coordinate transforms.

    This class is the anchor for the contract the 2D augmentations of ``kornia.augmentation`` inherit.
    Mix and 3D augmentations have their own bases and contracts.

    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:
        - the working layout is ``(B, C, H, W)`` float. A ``(C, H, W)`` input is promoted to ``(1, C, H, W)``
          and an ``(H, W)`` input to ``(1, 1, H, W)``; ``keepdim=True`` restores the input rank on the way out
          and never drops a real batch dimension. The dtype guard accepts ``float16``, ``bfloat16``, ``float32``
          and ``float64`` and raises ``TypeError`` on an integer tensor. The output keeps the input's device.
        - a wrong input rank raises :class:`~kornia.core.exceptions.InputRankError` with the same message from
          every entry point, the class, ``validate_tensor()`` and the containers. It is a ``ValueError`` and also a
          ``RuntimeError`` and an ``AssertionError``, the types those entry points raised before
          (`#4424 <https://github.com/kornia/kornia/issues/4424>`_). ``validate_tensor()`` accepts the ranks
          ``forward`` accepts.
        - this base samples ``p`` per sample and uses ``p_batch`` as a call-wide gate. ``same_on_batch=True``
          shares applicable sampled values across the batch. Concrete constructors need not expose ``p_batch``;
          it can be set as an attribute on any augmentation. A sample the gate skips comes back
          with its input values, its values cannot make the call raise, and where they are finite its gradient
          is the identity; a class whose transform checks input values or has an unbounded derivative runs it
          on 0.5 for skipped samples. An augmentation that changes the sample shape still raises ``ValueError``
          when the gate mixes applied and skipped samples (`#4497 <https://github.com/kornia/kornia/issues/4497>`_).
        - parameter sampling normally uses CPU defaults independently of the image device. Moving RNG state or
          samplers is incomplete for some generators, and returned parameter placement is a separate concern;
          see `#4426 <https://github.com/kornia/kornia/issues/4426>`_.
        - reproducibility goes through torch's global generators; there is no per-instance generator.
          ``generator=`` raises at construction; in ``forward`` it emits ``FutureWarning`` and is ignored,
          like other unknown keyword overrides
          (`#4427 <https://github.com/kornia/kornia/issues/4427>`_). :doc:`/get-started/conventions` states the
          seeding, ``DataLoader``-worker, parameter-placement and serialization rules.
        - the last draw is kept in ``_params``; ``forward(x, params=...)`` replaces that dict wholesale, stores the
          caller's dict by reference and, if ``batch_prob`` is absent, inserts an all-true gate into it. Replaying
          parameters reproduces the output, except for :class:`RandomDissolving`, whose VAE latents are drawn
          during application and are not stored.
        - with static ``p=1.0, p_batch=1.0`` every sample is transformed: a ``batch_prob`` put into ``params`` is not
          consulted by the image, the transformation matrix, the labels or ``inverse``, in eager and compiled runs
          alike (`#5585 <https://github.com/kornia/kornia/issues/5585>`_). Pass ``p < 1`` to skip samples by hand,
          which every one of those paths honors.
        - a ``_param_generator.*`` range buffer in ``state_dict()`` updates the samplers when loading changes it, and
          a learnable range is read before each draw; see :doc:`/get-started/conventions` for the classes this leaves
          out (`#4428 <https://github.com/kornia/kornia/issues/4428>`_).
        - an empty batch gives an empty output, except on a minority of classes that raise on ``B = 0``
          (`#4429 <https://github.com/kornia/kornia/issues/4429>`_).
        - rotation-like parameters are in degrees, and a positive angle turns the image counter-clockwise as
          displayed (top-left origin, y pointing down), as :func:`~kornia.geometry.transform.rotate` documents;
          :class:`RandomAffine` turns clockwise (`#4408 <https://github.com/kornia/kornia/issues/4408>`_).
        - ``torch.jit.script`` is not supported; ``torch.compile(fullgraph=True)`` works for some augmentations
          and flags only.

    See Also:
        - :class:`GeometricAugmentationBase2D`: adds coordinate-aware geometric transform hooks.

    """

    def validate_tensor(self, input: torch.Tensor) -> None:
        """Check that the input has a float dtype and one of the ranks ``forward`` accepts: 2, 3 or 4."""
        _validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, float16, float32, float64])
        if len(input.shape) not in (2, 3, 4):
            _raise_input_rank_error(input.shape, _IMAGE_SHAPES)

    @_input_metadata_only
    def transform_tensor(
        self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = True
    ) -> torch.Tensor:
        """Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
        _validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, float16, float32, float64])

        if shape is None:
            return _transform_input(input)

        return _transform_input_by_shape(input, reference_shape=shape, match_channel=match_channel)


class RigidAffineAugmentationBase2D(AugmentationBase2D):
    r"""Record a matrix for a custom 2D transform, applied per sample with probability ``p`` (default 0.5).

    ``output = MyAugmentation(...)(input)`` records a ``(B, 3, 3)`` matrix once a subclass implements
    ``compute_transformation`` and ``apply_transform``. This base manages matrix sampling and storage;
    use :class:`GeometricAugmentationBase2D` for coordinate transforms or :class:`IntensityAugmentationBase2D`
    for value-only operations.

    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:
        - a subclass implements :meth:`compute_transformation`, which returns the ``(B, 3, 3)`` matrix of the
          sampled transform, and ``apply_transform`` for images. Direct mask, box, and keypoint handlers are
          incomplete on this base; inherit the geometric base for its matrix-based handlers.
          :class:`~kornia.augmentation.container.AugmentationSequential` calls the subclass's mask, box and
          keypoint handlers with ``transform_matrix`` as ``transform``, as it does for a geometric child, and
          raises ``NotImplementedError`` for a registered data key whose handler is missing.
        - the matrix of the last call is readable as ``transform_matrix``. Subclasses opt into lazy construction
          with ``_compute_matrix_lazily``; a lazy matrix keeps only the input's shape, dtype and device, unless the
          subclass overrides ``transform_tensor``, ``generate_transformation_matrix``, ``compute_transformation``
          or ``identity_matrix``, in which case the input is kept until the matrix is read or replaced.
        - this base does not implement an inverse operation.

    See Also:
        - :class:`GeometricAugmentationBase2D`: applies and records 2D geometric transformations.

    """

    _transform_matrix: Optional[torch.Tensor] = None
    # Set True on subclasses whose ``apply_transform`` ignores the transform matrix (e.g. flips):
    # the image output never reads it, so building it every forward is pure overhead. When True,
    # ``apply_func`` defers the matrix and ``transform_matrix`` computes it on first access.
    _compute_matrix_lazily: bool = False
    _lazy_matrix_args: Optional[_LazyMatrixArgs] = None
    _transform_matrix_params: Optional[Dict[str, Any]] = None
    _transform_matrix_params_snapshot: Optional[Tuple[Tuple[str, Any, int], ...]] = None

    @staticmethod
    def _params_snapshot(params: Dict[str, Any]) -> Tuple[Tuple[str, Any, int], ...]:
        """Return each value of ``params`` with the version counter of each tensor value.

        The values themselves are kept, not their ``id()``: a replaced tensor that is freed can hand its address to the
        next tensor. An inference tensor has no version counter, so only its replacement is seen, not an in-place edit
        made inside ``torch.inference_mode``.
        """
        return tuple(
            (key, value, value._version if isinstance(value, torch.Tensor) and not value.is_inference() else -1)
            for key, value in params.items()
        )

    def _matrix_matches_params(self, params: Dict[str, Any]) -> bool:
        """Whether the recorded matrix was computed from ``params`` as they are now, not before a caller edited them."""
        if self._transform_matrix_params is not params:
            return False
        recorded = self._transform_matrix_params_snapshot
        if recorded is None:
            # An image call inside a Dynamo capture records no snapshot: Dynamo cannot trace ``is_inference`` and reads
            # each version counter as a new unbacked symbol. Within one compiled call nothing edits the params between
            # the image and its annotations, so the dict's identity is enough there.
            return is_compiling()
        current = self._params_snapshot(params)
        if len(recorded) != len(current):
            return False
        return all(k0 == k1 and v0 is v1 and n0 == n1 for (k0, v0, n0), (k1, v1, n1) in zip(recorded, current))

    def _record_matrix_params(self, params: Dict[str, Any]) -> None:
        """Record the params dict the image call was given, and its values, next to the matrix computed from it."""
        if not is_exporting():
            self._transform_matrix_params = params
            self._transform_matrix_params_snapshot = None if is_compiling() else self._params_snapshot(params)

    @property
    def transform_matrix(self) -> Optional[torch.Tensor]:
        if self._transform_matrix is None and self._lazy_matrix_args is not None:
            matrix_input, params, flags = self._lazy_matrix_args
            in_tensor = matrix_input.materialize() if isinstance(matrix_input, _InputMetadata) else matrix_input
            self._transform_matrix = self.generate_transformation_matrix(in_tensor, params, flags)
            self._lazy_matrix_args = None
        return self._transform_matrix

    @_input_metadata_only
    def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
        """Return 3x3 identity matrix."""
        return eye_like(3, input)

    def compute_transformation(
        self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
    ) -> torch.Tensor:
        raise NotImplementedError

    @_input_metadata_only
    def generate_transformation_matrix(
        self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
    ) -> torch.Tensor:
        """Generate transformation matrices with the given input and param settings."""
        batch_prob = params["batch_prob"]
        to_apply = torch.atleast_1d(batch_prob > 0.5)

        in_tensor = self.transform_tensor(input)

        trans_matrix_applied = self.compute_transformation(in_tensor, params=params, flags=flags)

        if self.p == 1.0 and self.p_batch == 1.0:
            # Always applied (static probabilities): the blend selects the computed matrix
            # everywhere, so it equals `trans_matrix_applied`. Skip building the identity and
            # the `where` — this is a hot per-call cost (~40% of a flip's forward is the matrix
            # path) that the image output never needs. Mirrors the `transform_inputs` fast path.
            trans_matrix = trans_matrix_applied
            if is_autocast_enabled():
                trans_matrix = trans_matrix.type(input.dtype)
            return trans_matrix

        trans_matrix_identity = self.identity_matrix(in_tensor)

        if is_autocast_enabled():
            trans_matrix_applied = trans_matrix_applied.type(input.dtype)
            trans_matrix_identity = trans_matrix_identity.type(input.dtype)

        # If batch sizes line up, do the where-blend. Otherwise (e.g. VideoSequential
        # passes B-sized batch_prob into a B*T-sized input) fall back to all-or-nothing.
        if trans_matrix_applied.shape[0] == to_apply.shape[0] == trans_matrix_identity.shape[0]:
            to_apply_expanded = _to_device_nonblocking(
                to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1))), trans_matrix_applied.device
            )
            trans_matrix = torch.where(to_apply_expanded, trans_matrix_applied, trans_matrix_identity)
        else:
            trans_matrix = trans_matrix_applied if bool(to_apply.any()) else trans_matrix_identity

        return trans_matrix

    def inverse_inputs(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        raise NotImplementedError

    def inverse_masks(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        raise NotImplementedError

    def inverse_boxes(
        self,
        input: Boxes,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> Boxes:
        raise NotImplementedError

    def inverse_keypoints(
        self,
        input: Keypoints,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> Keypoints:
        raise NotImplementedError

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

    def apply_func(
        self, in_tensor: torch.Tensor, params: Dict[str, torch.Tensor], flags: Optional[Dict[str, Any]] = None
    ) -> torch.Tensor:
        if flags is None:
            flags = self.flags
        # ``forward`` committed the caller's params dict as ``_params`` before overriding a copy for this call (and
        # ``transform_inputs`` commits that copy). Pair the caller's dict and a snapshot of its values with the matrix,
        # so the container's annotation handlers can tell a replay of this draw from another draw or an edited dict.
        matrix_params = self._params
        if self._compute_matrix_lazily:
            # apply_transform ignores the matrix for these ops, so don't build it here; defer to
            # the first `.transform_matrix` access (e.g. AugmentationSequential propagating to
            # boxes/keypoints/masks). A standalone flip that never reads the matrix skips it.
            matrix_input: Union[torch.Tensor, _InputMetadata] = in_tensor
            # Check the implementations, not the class: custom overrides may read
            # pixels even when they inherit the built-in's lazy-computation flag.
            if all(
                getattr(method, "_kornia_input_metadata_only", None) is getattr(method, "__func__", method)
                for method in (
                    self.transform_tensor,
                    self.generate_transformation_matrix,
                    self.compute_transformation,
                    self.identity_matrix,
                )
            ):
                # PyTorch 2.5 snapshots torch.Size as a tuple during non-strict export.
                matrix_input = _InputMetadata(tuple(in_tensor.shape), in_tensor.dtype, in_tensor.device)
            self._commit_state(transform_matrix=None, lazy_matrix_args=(matrix_input, params, flags))
            self._record_matrix_params(matrix_params)
            return self.transform_inputs(in_tensor, params, flags, None)

        trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags)
        output = self.transform_inputs(in_tensor, params, flags, trans_matrix)
        self._commit_state(transform_matrix=trans_matrix, lazy_matrix_args=None)
        self._record_matrix_params(matrix_params)

        return output
