# 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 numbers import Integral

import torch
from torch import nn
from torch.nn.functional import interpolate

from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE

from .blur import box_blur
from .filter import _to_floating
from .kernels import _unpack_2d_ks


def _check_subsample(subsample: int) -> None:
    def msg() -> str:
        return f"`subsample` must be a positive integer. Got: {subsample!r}"

    KORNIA_CHECK_TYPE(subsample, Integral, lambda: f"{msg()} ({type(subsample).__name__})")
    # ``bool`` is an ``int``, and ``subsample=True`` would otherwise run as 1.
    KORNIA_CHECK(not isinstance(subsample, bool) and subsample >= 1, msg)


def _subsample_indices(size: int, subsample: int, device: torch.device) -> torch.Tensor:
    """Return the pixels an axis of ``size`` pixels keeps when it is subsampled by ``subsample``.

    ``max(size // subsample, 1)`` pixels, never none: an axis shorter than ``subsample`` keeps its first pixel. Pixel
    ``i`` of the subsampled axis is the one nearest to ``(i + 0.5) * size / rows - subsample / 2``, rounding a tie up:
    where the bilinear upsample (``align_corners=False``) puts it back, less the ``(subsample - 1) / 2`` offset of
    taking every ``subsample``-th pixel. On a ``size`` that is a multiple of ``subsample`` that is pixel
    ``subsample * i`` exactly, and elsewhere the offset stays the same along the axis instead of drifting by up to a
    pixel, as ``floor(i * size / rows)`` would. Integer arithmetic, so it is exact in every dtype.
    """
    rows = max(size // subsample, 1)
    i = torch.arange(rows, device=device)
    return ((2 * i + 1) * size + rows * (1 - subsample)).div(2 * rows, rounding_mode="floor").clamp(0, size - 1)


def _preprocess_fast_guided_blur(
    guidance: torch.Tensor, input: torch.Tensor, kernel_size: tuple[int, int] | int, subsample: int = 1
) -> tuple[torch.Tensor, torch.Tensor, tuple[int, int]]:
    ky, kx = _unpack_2d_ks(kernel_size)
    if subsample > 1:
        rows = _subsample_indices(guidance.shape[-2], subsample, guidance.device)
        cols = _subsample_indices(guidance.shape[-1], subsample, guidance.device)
        guidance_sub = guidance.index_select(-2, rows).index_select(-1, cols)
        input_sub = guidance_sub if input is guidance else input.index_select(-2, rows).index_select(-1, cols)
        ky, kx = ((k - 1) // subsample + 1 for k in (ky, kx))
    else:
        guidance_sub = guidance
        input_sub = input
    return guidance_sub, input_sub, (ky, kx)


def _guided_blur_grayscale_guidance(
    guidance: torch.Tensor,
    input: torch.Tensor,
    kernel_size: tuple[int, int] | int,
    eps: float | torch.Tensor,
    border_type: str = "reflect",
    subsample: int = 1,
    separable: bool = False,
) -> torch.Tensor:
    guidance_sub, input_sub, kernel_size = _preprocess_fast_guided_blur(guidance, input, kernel_size, subsample)

    mean_I = box_blur(guidance_sub, kernel_size, border_type, separable=separable)
    corr_I = box_blur(guidance_sub.square(), kernel_size, border_type, separable=separable)
    # Fuse the multiply/subtract to avoid an image-sized intermediate.
    var_I = torch.addcmul(corr_I, mean_I, mean_I, value=-1)

    if input is guidance:
        mean_p = mean_I
        cov_Ip = var_I

    else:
        mean_p = box_blur(input_sub, kernel_size, border_type, separable=separable)
        corr_Ip = box_blur(guidance_sub * input_sub, kernel_size, border_type, separable=separable)
        cov_Ip = torch.addcmul(corr_Ip, mean_I, mean_p, value=-1)

    if isinstance(eps, torch.Tensor):
        eps = eps.view(-1, 1, 1, 1)  # N -> NCHW

    a = cov_Ip / (var_I + eps)
    b = torch.addcmul(mean_p, a, mean_I, value=-1)

    mean_a = box_blur(a, kernel_size, border_type, separable=separable)
    mean_b = box_blur(b, kernel_size, border_type, separable=separable)

    if subsample > 1:
        # back to the input's own size: it is ``subsample`` times the subsampled one only if it is a multiple of it
        mean_a = interpolate(mean_a, size=guidance.shape[-2:], mode="bilinear")
        mean_b = interpolate(mean_b, size=guidance.shape[-2:], mode="bilinear")

    return torch.addcmul(mean_b, mean_a, guidance)


def _guided_blur_multichannel_guidance(
    guidance: torch.Tensor,
    input: torch.Tensor,
    kernel_size: tuple[int, int] | int,
    eps: float | torch.Tensor,
    border_type: str = "reflect",
    subsample: int = 1,
    separable: bool = False,
) -> torch.Tensor:
    # One compute dtype for the whole path: ``mean_I @ a`` needs ``mean_I`` in the dtype ``a`` is solved in, so a
    # guidance narrower than ``input`` (float16, float32 or uint8 next to float64) is promoted to the pair's dtype.
    # ``Tensor.to`` is a no-op when the dtypes already match, so every other pair is unaffected.
    guidance = guidance.to(torch.promote_types(guidance.dtype, input.dtype))
    guidance_sub, input_sub, kernel_size = _preprocess_fast_guided_blur(guidance, input, kernel_size, subsample)
    B, C, H, W = guidance_sub.shape
    # The input channel count is spelled out instead of inferred with ``-1``: an empty batch has no elements, so
    # ``reshape``/``view`` cannot infer that size and raise (#4429).
    C_in = input.shape[1]

    mean_I = box_blur(guidance_sub, kernel_size, border_type, separable=separable).permute(0, 2, 3, 1)
    II = (guidance_sub.unsqueeze(1) * guidance_sub.unsqueeze(2)).flatten(1, 2)
    corr_I = box_blur(II, kernel_size, border_type, separable=separable).permute(0, 2, 3, 1)
    var_I = torch.addcmul(corr_I.reshape(B, H, W, C, C), mean_I.unsqueeze(-2), mean_I.unsqueeze(-1), value=-1)

    if guidance is input:
        mean_p = mean_I
        cov_Ip = var_I

    else:
        mean_p = box_blur(input_sub, kernel_size, border_type, separable=separable).permute(0, 2, 3, 1)
        Ip = (input_sub.unsqueeze(1) * guidance_sub.unsqueeze(2)).flatten(1, 2)
        corr_Ip = box_blur(Ip, kernel_size, border_type, separable=separable).permute(0, 2, 3, 1)
        cov_Ip = torch.addcmul(corr_Ip.reshape(B, H, W, C, C_in), mean_p.unsqueeze(-2), mean_I.unsqueeze(-1), value=-1)

    if isinstance(eps, torch.Tensor):
        _eps = torch.eye(C, device=guidance.device, dtype=guidance.dtype).view(1, 1, 1, C, C) * eps.view(-1, 1, 1, 1, 1)
    else:
        _eps = guidance.new_full((C,), eps).diag().view(1, 1, 1, C, C)
    # ``torch.linalg.solve`` needs both operands in one dtype, and it has no half-precision LU
    # kernel: a float16/bfloat16 guidance dies here with ``NotImplementedError: "lu_cpu" not
    # implemented for 'Half'``, and on MPS it aborts the process instead of raising. A tensor
    # ``eps`` also takes part in promotion, so ``A`` can come out wider than ``cov_Ip`` -- the
    # common ``eps=torch.tensor(0.1)`` is float32 -- and ``solve`` rejects the mismatched pair.
    # So pick a single dtype for both operands, lifting half to float32, and cast the solution
    # back. Deliberately not ``_torch_solve_cast``: that promotes float32 to float64, which would
    # change the results of the default path and pay for a float64 solve at every pixel.
    # ``Tensor.to`` is a no-op when the dtype already matches, so an all-float32 or all-float64
    # call takes exactly the path it took before.
    A = var_I + _eps
    solve_dtype = torch.promote_types(A.dtype, cov_Ip.dtype)
    if solve_dtype in (torch.float16, torch.bfloat16):
        solve_dtype = torch.float32
    a = torch.linalg.solve(A.to(solve_dtype), cov_Ip.to(solve_dtype)).to(cov_Ip.dtype)
    b = mean_p - (mean_I.unsqueeze(-2) @ a).squeeze(-2)  # B, H, W, C_input

    mean_a = box_blur(a.flatten(-2).permute(0, 3, 1, 2), kernel_size, border_type, separable=separable)
    mean_b = box_blur(b.permute(0, 3, 1, 2), kernel_size, border_type, separable=separable)

    if subsample > 1:
        mean_a = interpolate(mean_a, size=guidance.shape[-2:], mode="bilinear")
        mean_b = interpolate(mean_b, size=guidance.shape[-2:], mode="bilinear")
    mean_a = mean_a.view(B, C, C_in, *guidance.shape[-2:])

    # torch.einsum might not be contiguous, thus mean_b is the first argument
    return mean_b + torch.einsum("BCHW,BCcHW->BcHW", guidance, mean_a)


def guided_blur(
    guidance: torch.Tensor,
    input: torch.Tensor,
    kernel_size: tuple[int, int] | int,
    eps: float | torch.Tensor,
    border_type: str = "reflect",
    subsample: int = 1,
    separable: bool = False,
) -> torch.Tensor:
    r"""Smooth an image with a guided filter, which follows the edges of a guidance image.

    ``out = guided_blur(guidance, input, kernel_size, eps)`` smooths a ``(B, C_i, H, W)`` ``input`` along the edges of a
    ``(B, C_g, H, W)`` ``guidance`` by fitting a local linear model :cite:`he2010guided`. ``subsample`` above 1 selects
    the fast guided filter :cite:`he2015fast`. Pass the same tensor twice to smooth an image along its own edges.

    .. image:: _static/img/guided_blur.png

    Convention:
        - ``guidance`` comes first and ``input`` second, the opposite of
          :func:`~kornia.filters.joint_bilateral_blur`.
        - ``kernel_size`` is the whole ``(kH, kW)`` window, ``2 * r + 1`` for the radius ``r`` of
          :cite:`he2010guided`. The window means are :func:`~kornia.filters.box_blur`'s, so the border modes and
          the anchor of an even size follow its Convention block.
        - ``eps`` is added to the local variance of ``guidance``, so it is in squared guidance units: guidance and
          input scaled by ``s``, filtered with ``eps * s**2``, give the result scaled by ``s``.
          :ref:`Filtering <filtering-conventions>` maps the arguments onto OpenCV's ``guidedFilter``.
        - An integer or bool ``guidance`` or ``input`` is converted to float32 before the covariance products, on its
          own scale, and the result has the promoted dtype of the two: a float16 ``input`` with a uint8 ``guidance``
          returns float32, where :func:`~kornia.filters.joint_bilateral_blur` keeps ``input``'s dtype. With grayscale
          guidance, a tensor-valued ``eps`` also participates in result dtype promotion; multichannel guidance
          retains the promoted dtype of ``guidance`` and ``input``.
        - A float16 or bfloat16 ``guidance`` or ``input`` is converted to float32 before the window statistics, and
          the coefficients are solved in float32 as well (in float64 with a float64 tensor ``eps``). Autocast is
          disabled inside the filter, so a float32 call in an autocast region returns float32. The result has the
          dtype of the rule above.

    Args:
        guidance: image whose edges are kept, with shape ``(B, C_g, H, W)``.
        input: image to smooth, with shape ``(B, C_i, H, W)``.
        kernel_size: window ``(kH, kW)`` in pixels, or one integer for both.
        eps: regularization of the local variance; smaller values keep more edges.
        border_type: padding mode, ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
        subsample: subsampling factor of the fast guided filter, a positive integer; ``1`` means none. Guidance and
          input are subsampled by nearest neighbour and the coefficient maps resized back to the input's size, so ``H``
          and ``W`` need not be multiples of it.
        separable: ``True`` applies the window means as two 1D passes, which saves work for large windows.

    Returns:
        the smoothed image with shape ``(B, C_i, H, W)``.

    Raises:
        TypeCheckError: if ``subsample`` is not an integer (NumPy integers are accepted).
        BaseError: if ``subsample`` is not positive, or is a ``bool``.

    See Also:
        - :class:`GuidedBlur`: the module form.
        - :func:`joint_bilateral_blur`: another filter that follows a guidance image, with sigmas in place of
          ``eps``, and ``input`` first.
        - :func:`bilateral_blur`: weights each neighbour by its distance and colour instead of fitting a linear model.

    Example:
        >>> guidance = torch.rand(2, 3, 5, 5)
        >>> input = torch.rand(2, 4, 5, 5)
        >>> output = guided_blur(guidance, input, 3, 0.1)
        >>> output.shape
        torch.Size([2, 4, 5, 5])

    """
    KORNIA_CHECK_IS_TENSOR(guidance)
    KORNIA_CHECK_SHAPE(guidance, ["B", "C", "H", "W"])
    _check_subsample(subsample)
    # A NumPy integer passes the check. Its arithmetic stays in its own dtype, so ``(k - 1) // subsample + 1`` can
    # overflow it (``numpy.uint8(2)`` with ``kernel_size=301``): continue with a Python ``int``.
    subsample = int(subsample)
    if input is not guidance:
        KORNIA_CHECK_IS_TENSOR(input)
        KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
        KORNIA_CHECK(
            (guidance.shape[0] == input.shape[0]) and (guidance.shape[-2:] == input.shape[-2:]),
            "guidance and input should have the same batch size and spatial dimensions",
        )

    input_is_guidance = input is guidance
    guidance = _to_floating(guidance)
    input = guidance if input_is_guidance else _to_floating(input)
    output_dtype = torch.promote_types(guidance.dtype, input.dtype)
    # E[g*g] - E[g]*E[g] loses the local variance in half precision, before
    # even a promoted solve can help. Promote before all window statistics.
    if guidance.dtype in (torch.float16, torch.bfloat16):
        guidance = guidance.float()
    if input_is_guidance:
        input = guidance
    elif input.dtype in (torch.float16, torch.bfloat16):
        input = input.float()

    if guidance.shape[1] == 1:
        blur = _guided_blur_grayscale_guidance
        if isinstance(eps, torch.Tensor):
            output_dtype = torch.promote_types(output_dtype, eps.dtype)
    else:
        blur = _guided_blur_multichannel_guidance
    # Autocast would lower the box-filter convolutions back to half precision. A meta tensor carries only a shape and
    # ``torch.autocast("meta")`` raises, so the CPU autocast stands in for it.
    device_type = "cpu" if guidance.device.type == "meta" else guidance.device.type
    with torch.autocast(device_type=device_type, enabled=False):
        return blur(
            guidance,
            input,
            kernel_size,
            eps,
            border_type,
            subsample,
            separable=separable,
        ).to(output_dtype)


class GuidedBlur(nn.Module):
    r"""Smooth an image with a stored guided filter (module form).

    ``blur = GuidedBlur(kernel_size, eps)`` stores its arguments, and ``out = blur(guidance, input)`` is
    :func:`guided_blur` on a ``(B, C_g, H, W)`` guidance and a ``(B, C_i, H, W)`` image.

    Convention:
        See the Convention block on :func:`~kornia.filters.guided_blur`.

    Args:
        kernel_size: window ``(kH, kW)`` in pixels, or one integer for both.
        eps: regularization of the local variance, as in :func:`guided_blur`.
        border_type: padding mode, as in :func:`guided_blur`.
        subsample: subsampling factor of the fast guided filter, a positive integer; ``1`` means none.
        separable: ``True`` applies the window means as two 1D passes.

    Raises:
        TypeCheckError: if ``subsample`` is not an integer (NumPy integers are accepted).
        BaseError: if ``subsample`` is not positive, or is a ``bool``. Both are raised by the constructor.

    Shape:
        - Input: ``(B, C_g, H, W)``, ``(B, C_i, H, W)``
        - Output: ``(B, C_i, H, W)``

    See Also:
        - :func:`guided_blur`: the one-call form.
        - :class:`JointBilateralBlur`: another filter that follows a guidance image, with the input first.

    Example:
        >>> guidance = torch.rand(2, 3, 5, 5)
        >>> input = torch.rand(2, 4, 5, 5)
        >>> blur = GuidedBlur(3, 0.1)
        >>> output = blur(guidance, input)
        >>> output.shape
        torch.Size([2, 4, 5, 5])

    """

    def __init__(
        self,
        kernel_size: tuple[int, int] | int,
        eps: float,
        border_type: str = "reflect",
        subsample: int = 1,
        separable: bool = False,
    ) -> None:
        super().__init__()
        _check_subsample(subsample)
        self.kernel_size = kernel_size
        self.eps = eps
        self.border_type = border_type
        self.subsample = subsample
        self.separable = separable

    def __repr__(self) -> str:
        return (
            f"{self.__class__.__name__}"
            f"(kernel_size={self.kernel_size}, "
            f"eps={self.eps}, "
            f"border_type={self.border_type}, "
            f"subsample={self.subsample}, "
            f"separable={self.separable})"
        )

    def forward(self, guidance: torch.Tensor, input: torch.Tensor) -> torch.Tensor:
        """Filter an input tensor with local linear guidance.

        Guided filtering assumes that, inside each local window, the output can
        be represented as a linear transform of the ``guidance`` image. This
        makes the filter useful for edge-aware smoothing: flat regions are
        averaged, while strong structures in the guidance tensor are preserved
        in the filtered result.

        Args:
            guidance: Guidance tensor with shape ``(B, C_g, H, W)``, where
                :math:`B` is the batch size, :math:`C_g` is the number of
                guidance channels, :math:`H` is the height, and :math:`W` is
                the width.
            input: Tensor to filter with shape ``(B, C_i, H, W)``, where
                :math:`C_i` is the number of channels in the signal being
                smoothed. Its batch and spatial dimensions must equal those
                of ``guidance``.

        Returns:
            Tensor with shape ``(B, C_i, H, W)`` containing the
            edge-aware filtered version of ``input``.
        """
        return guided_blur(
            guidance,
            input,
            kernel_size=self.kernel_size,
            eps=self.eps,
            border_type=self.border_type,
            subsample=self.subsample,
            separable=self.separable,
        )
