# Copyright 2025 Qwen-Image Team and 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.


from typing import List

import PIL.Image
import torch

from ...utils import logging
from ..modular_pipeline import SequentialPipelineBlocks
from ..modular_pipeline_utils import InsertableDict, OutputParam
from .before_denoise import (
    QwenImageLayeredPrepareLatentsStep,
    QwenImageLayeredRoPEInputsStep,
    QwenImageLayeredSetTimestepsStep,
)
from .decoders import (
    QwenImageLayeredAfterDenoiseStep,
    QwenImageLayeredDecoderStep,
)
from .denoise import (
    QwenImageLayeredDenoiseStep,
)
from .encoders import (
    QwenImageEditProcessImagesInputStep,
    QwenImageLayeredGetImagePromptStep,
    QwenImageLayeredPermuteLatentsStep,
    QwenImageLayeredResizeStep,
    QwenImageTextEncoderStep,
    QwenImageVaeEncoderStep,
)
from .inputs import (
    QwenImageLayeredAdditionalInputsStep,
    QwenImageTextInputsStep,
)


logger = logging.get_logger(__name__)


# ====================
# 1. TEXT ENCODER
# ====================


class QwenImageLayeredTextEncoderStep(SequentialPipelineBlocks):
    """Text encoder that takes text prompt, will generate a prompt based on image if not provided."""

    model_name = "qwenimage-layered"
    block_classes = [
        QwenImageLayeredResizeStep(),
        QwenImageLayeredGetImagePromptStep(),
        QwenImageTextEncoderStep(),
    ]
    block_names = ["resize", "get_image_prompt", "encode"]

    @property
    def description(self) -> str:
        return "QwenImage-Layered Text encoder step that encode the text prompt, will generate a prompt based on image if not provided."


# ====================
# 2. VAE ENCODER
# ====================


# Edit VAE encoder
class QwenImageLayeredVaeEncoderStep(SequentialPipelineBlocks):
    model_name = "qwenimage-layered"
    block_classes = [
        QwenImageLayeredResizeStep(),
        QwenImageEditProcessImagesInputStep(),
        QwenImageVaeEncoderStep(),
        QwenImageLayeredPermuteLatentsStep(),
    ]
    block_names = ["resize", "preprocess", "encode", "permute"]

    @property
    def description(self) -> str:
        return "Vae encoder step that encode the image inputs into their latent representations."


# ====================
# 3. DENOISE (input -> prepare_latents -> set_timesteps -> prepare_rope_inputs -> denoise -> after_denoise)
# ====================


# assemble input steps
class QwenImageLayeredInputStep(SequentialPipelineBlocks):
    model_name = "qwenimage-layered"
    block_classes = [
        QwenImageTextInputsStep(),
        QwenImageLayeredAdditionalInputsStep(image_latent_inputs=["image_latents"]),
    ]
    block_names = ["text_inputs", "additional_inputs"]

    @property
    def description(self):
        return (
            "Input step that prepares the inputs for the layered denoising step. It:\n"
            " - make sure the text embeddings have consistent batch size as well as the additional inputs.\n"
            " - update height/width based `image_latents`, patchify `image_latents`."
        )


# Qwen Image Layered (image2image) core denoise step
class QwenImageLayeredCoreDenoiseStep(SequentialPipelineBlocks):
    model_name = "qwenimage-layered"
    block_classes = [
        QwenImageLayeredInputStep(),
        QwenImageLayeredPrepareLatentsStep(),
        QwenImageLayeredSetTimestepsStep(),
        QwenImageLayeredRoPEInputsStep(),
        QwenImageLayeredDenoiseStep(),
        QwenImageLayeredAfterDenoiseStep(),
    ]
    block_names = [
        "input",
        "prepare_latents",
        "set_timesteps",
        "prepare_rope_inputs",
        "denoise",
        "after_denoise",
    ]

    @property
    def description(self):
        return "Core denoising workflow for QwenImage-Layered img2img task."

    @property
    def outputs(self):
        return [
            OutputParam(
                name="latents", type_hint=torch.Tensor, description="The latents generated by the denoising step"
            ),
        ]


# ====================
# 4. AUTO BLOCKS & PRESETS
# ====================

LAYERED_AUTO_BLOCKS = InsertableDict(
    [
        ("text_encoder", QwenImageLayeredTextEncoderStep()),
        ("vae_encoder", QwenImageLayeredVaeEncoderStep()),
        ("denoise", QwenImageLayeredCoreDenoiseStep()),
        ("decode", QwenImageLayeredDecoderStep()),
    ]
)


class QwenImageLayeredAutoBlocks(SequentialPipelineBlocks):
    model_name = "qwenimage-layered"
    block_classes = LAYERED_AUTO_BLOCKS.values()
    block_names = LAYERED_AUTO_BLOCKS.keys()

    @property
    def description(self):
        return "Auto Modular pipeline for layered denoising tasks using QwenImage-Layered."

    @property
    def outputs(self):
        return [
            OutputParam(name="images", type_hint=List[List[PIL.Image.Image]], description="The generated images"),
        ]
