# 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 import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.core.utils import _clamp_unit_range
from kornia.filters import StableDiffusionDissolving


class RandomDissolving(IntensityAugmentationBase2D):
    r"""Dissolve images with a Stable Diffusion model, applied to the whole batch with probability ``p`` (default 0.5).

    ``output = RandomDissolving(step_range, version, ...)(input)`` applies one sampled reverse-diffusion step to the
    selected batch of images. It needs the optional ``diffusers`` dependency and a compatible Stable Diffusion model.

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

    Based on :cite:`shi2024dissolving`, the dissolving transformation is essentially applying one-step
    reverse diffusion. Our implementation currently supports the HuggingFace implementations of SD 1.4, SD 1.5
    and SD XL; once ``diffusers`` is importable, any other ``version`` raises ``NotImplementedError``
    with the unsupported value and the supported versions
    (without it, construction fails on the optional-dependency prompt before the version is looked at).

    .. list-table::
        :widths: 32 32 32
        :header-rows: 1

        * - SD 1.4
          - SD 1.5
          - SD XL
        * - .. figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.4.png
          - .. figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.5.png
          - .. figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-xl.png

    Args:
        p: probability of applying the transformation, drawn once for the whole batch.
        version: the version of the stable diffusion model. Options: ``"1.4"``, ``"1.5"``, ``"xl"``.
        step_range: the step range of the diffusion model steps. Higher the step, stronger
                    the dissolving effects.
        keepdim: whether to keep the output shape the same as input (True) or broadcast it
                 to the batch form (False).
        **kwargs: additional arguments for `.from_pretrained` for HF StableDiffusionPipeline.

    Shape:
        - Input: ``(C, H, W)`` or ``(B, C, H, W)``.
        - Output: ``(B, C, H, W)``

    Convention:
        - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped
          into the same range. This applies only to samples selected by the probability gate.
        - the clamped input is encoded by the Stable Diffusion VAE; its decoded result is also clamped.

    .. note::
        The transform is delegated to ``kornia.filters.StableDiffusionDissolving``, which the constructor
        builds: instantiating this class needs the optional ``diffusers`` package and, on a cold cache,
        downloads a Stable Diffusion checkpoint at that point -- the ``from_pretrained`` call is in that
        class's own constructor, not on the first forward.

    See Also:
        - :class:`RandomErasing`: removes a rectangle without a diffusion model.
        - :class:`~kornia.filters.StableDiffusionDissolving`: the model itself, with a step you choose and an input it
          does not clamp.

    """

    def __init__(
        self,
        step_range: Tuple[float, float] = (100, 500),
        version: str = "1.5",
        p: float = 0.5,
        keepdim: bool = False,
        **kwargs: Any,
    ) -> None:
        super().__init__(p=p, same_on_batch=True, keepdim=keepdim)
        self.step_range = step_range
        self._dslv = StableDiffusionDissolving(version, **kwargs)
        self._param_generator = rg.PlainUniformGenerator((self.step_range, "step_range_factor", None, None))

    def apply_transform(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        input = _clamp_unit_range(input)
        return _clamp_unit_range(self._dslv(input, params["step_range_factor"][0].long().item()))
