# 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

import os
from typing import Any, Optional

import torch
from torch import nn

from kornia.config import kornia_config
from kornia.core import ImageSequential
from kornia.core.external import onnx
from kornia.geometry.transform import resize
from kornia.models.base import ModelBaseMixin
from kornia.onnx import ONNXSequential
from kornia.onnx.download import _relative_path_components
from kornia.onnx.utils import ONNXLoader, _cached_file_hint, _load_cached_json, _load_cached_onnx, io_name_conversion

from .preprocessor import PreprocessingLoader


class HFONNXComunnityModelLoader:
    """Initializes the ONNXComunnityModelLoader for onnx-community repo of Hugging Face.

    Args:
        model_name: The name of the model to load.
        model_type: The type of the model to load.
        cache_dir: The directory where models are cached locally. The model, its weights and its preprocessing
            config are stored in ``<cache_dir>/<model_name>/``.
            Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
        with_data: Whether to download the model weights such as `model.onnx_data`.

    Raises:
        ValueError: If ``model_name`` is absolute, has a drive (on Windows) or has an empty, ``.`` or ``..``
            component, which would put the cache outside ``cache_dir``.

    """

    def __init__(
        self, model_name: str, model_type: str = "model", cache_dir: Optional[str] = None, with_data: bool = False
    ) -> None:
        self.model_name = model_name
        self.model_type = model_type
        self.with_data = with_data

        if cache_dir is None:
            cache_dir = kornia_config.hub_onnx_dir
        # the model, its weights and its preprocessing config are cached in <cache_dir>/<model_name>/, so the name must
        # not leave cache_dir ("../x", an absolute path), where a file already there would be loaded without a download
        _relative_path_components(model_name, "model_name")
        self.cache_dir = os.path.join(cache_dir, self.model_name)
        self.model_url = (
            f"https://huggingface.co/onnx-community/{self.model_name}/resolve/main/onnx/{self.model_type}.onnx"
        )
        self.config_url = (
            f"https://huggingface.co/onnx-community/{self.model_name}/resolve/main/preprocessor_config.json"
        )

    def load_model(
        self,
        download: bool = True,
        io_name_mapping: Optional[dict[str, str]] = None,
        *,
        force_download: bool = False,
        **kwargs: Any,
    ) -> onnx.ModelProto:
        """Load the ONNX model file from the configured onnx-community repository.

        A model that is in the cache is used as it is, however old: pass ``force_download=True`` to fetch it again.

        Args:
            download: Whether to download the remote ONNX file when it is not already
                available in the local cache directory.
            io_name_mapping: Optional mapping used to rename ONNX graph input and
                output names after loading. This is useful when composing the model
                with Kornia pre-processing or post-processing graphs that expect
                specific tensor names.
            force_download: Whether to download the model, and its weights when ``with_data`` is set, again and replace
                the cached files, even when they are cached. The model is replaced before the weights are fetched: if
                the weights then fail to download, the cache holds the new model with the old weights, so call again
                with ``force_download=True`` before loading it. Needs ``download=True``.
            kwargs: Not used; any keyword raises ``TypeError``. Kept for compatibility.

        Returns:
            The loaded ONNX model graph. If ``io_name_mapping`` is provided, the graph
            is returned after its input and output names have been converted.
        """
        # <cache_dir>/<model_name>/<model_type>.onnx: the repository's own directory, where earlier releases cached
        # these models too, so they are not downloaded again
        file_path = ONNXLoader.download_to_cache(
            self.model_url,
            self.model_type,
            download,
            cache_dir=self.cache_dir,
            suffix=".onnx",
            force_download=force_download,
            **kwargs,
        )
        if self.with_data:  # beside the model, under the name the model refers to
            ONNXLoader.download_to_cache(
                f"{self.model_url}_data",
                self.model_type,
                download,
                cache_dir=self.cache_dir,
                suffix=".onnx_data",
                force_download=force_download,
                **kwargs,
            )
        onnx_model = _load_cached_onnx(file_path)

        if io_name_mapping is not None:
            onnx_model = io_name_conversion(onnx_model, io_name_mapping)

        return onnx_model

    def load_preprocessing(self, *, force_download: bool = False) -> ImageSequential:
        """Load the preprocessing pipeline described by the remote processor config.

        The Hugging Face onnx-community repositories store image preprocessing
        settings in ``preprocessor_config.json``. This method reads that JSON file and
        converts the supported operations, such as resize, rescale, and normalize, into
        a Kornia :class:`~kornia.core.ImageSequential` module.

        Args:
            force_download: Whether to download ``preprocessor_config.json`` again and replace the cached file, even
                when it is cached.

        Returns:
            Sequential Kornia image preprocessing module built from the repository
            configuration.
        """
        # <cache_dir>/<model_name>/preprocessor_config.json, beside the repository's model
        file_path = ONNXLoader.download_to_cache(
            self.config_url, "preprocessor_config.json", cache_dir=self.cache_dir, force_download=force_download
        )
        config = _load_cached_json(file_path)
        try:
            return PreprocessingLoader.from_json(config)
        except KeyError as exc:  # valid JSON that lacks what a processor config has: a file that is not the hub's
            exc.add_note(_cached_file_hint(file_path))
            raise


class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
    """ONNX model wrapper for Kornia pipelines loaded from onnx-community repositories.

    The wrapper combines an optional preprocessing graph, the core ONNX model, and an
    optional postprocessing graph into a single :class:`ONNXSequential` module. It also
    keeps references to the individual components so callers can export either the
    complete pipeline or only the model graph.

    Args:
        model: Main ONNX model graph.
        pre_processor: Optional ONNX graph executed before ``model``.
        post_processor: Optional ONNX graph executed after ``model``.
        name: Optional human-readable model name used for export filenames.
        auto_ir_version_conversion: Whether to allow automatic ONNX IR version
            conversion when composing the sequence.
        io_maps: Optional list with one list of ``(output, input)`` name pairs per joint between
            consecutive graphs (pre-processor, model, post-processor, of those given), as for
            :class:`~kornia.onnx.sequential.ONNXSequential`.
        resize: Optional torch module that resizes an image before the ONNX graphs, for a
            resize whose output size depends on the input size and so cannot be part of a
            graph with dynamic height and width. It is kept as ``self.resize``; the subclass
            that runs the graphs applies it (:class:`~kornia.models.depth_estimation.DepthEstimation`
            does), and it is not part of the graph :meth:`to_onnx` exports.
    """

    name: str = "onnx_community_model"

    def __init__(
        self,
        model: onnx.ModelProto,
        pre_processor: Optional[onnx.ModelProto] = None,
        post_processor: Optional[onnx.ModelProto] = None,
        name: Optional[str] = None,
        auto_ir_version_conversion: bool = True,
        io_maps: Optional[list[list[tuple[str, str]]]] = None,
        resize: Optional[nn.Module] = None,
    ) -> None:
        model_list = [] if pre_processor is None else [pre_processor]
        model_list.append(model)
        if post_processor is not None:
            model_list.append(post_processor)
        super().__init__(*model_list, auto_ir_version_conversion=auto_ir_version_conversion, io_maps=io_maps)
        if name is not None:
            self.name = name
        self.model = model
        self.pre_processor = pre_processor
        self.post_processor = post_processor
        self.resize = resize

    def resize_back(self, images: torch.Tensor, target_images: torch.Tensor) -> torch.Tensor:
        """Resize the input images back to the original size of target images.

        Args:
            images: The images to be resized, of shape :math:`(B, C, h, w)`.
            target_images: The target images whose size ``(H, W)`` is used as the reference for resizing.

        Returns:
            The resized images.

        Raises:
            TypeError: if ``target_images`` is not a tensor.

        """
        if isinstance(target_images, torch.Tensor):
            return resize(images, target_images.shape[-2:])
        raise TypeError(f"target_images must be a torch.Tensor, got {type(target_images).__name__}.")

    def to_onnx(
        self,
        onnx_name: Optional[str] = None,
        include_pre_and_post_processor: bool = True,
        save: bool = True,
        additional_metadata: Optional[list[tuple[str, str]]] = None,
        **kwargs: Any,
    ) -> onnx.ModelProto:
        """Export the ONNX model, alone or combined with its pre- and post-processing graphs, to ONNX format.

        Args:
            onnx_name:
                The name of the output ONNX file. If not provided, ``"kornia_<name>.onnx"`` is used, with the
                model's ``name``.
            include_pre_and_post_processor:
                Whether to include the pre-processor and post-processor graphs in the exported model. The
                ``resize`` stage runs in torch and is in neither graph: for a model that has one, the exported
                graph takes an image that is already resized, such as ``model.resize(image)``.
            save:
                If True, write the model to ``onnx_name``; it is returned either way.
            additional_metadata:
                Additional metadata to add to the exported model. It goes on a copy: the stored graphs, and a
                ``ModelProto`` the model was built from, are left as they are.
            kwargs: Additional keyword arguments of ``onnx.save``, used when ``save`` is True.

        Returns:
            A copy of the model or of the combined graph, with ``source``, ``version`` and ``additional_metadata``.

        """
        if onnx_name is None:
            onnx_name = f"kornia_{self.name}.onnx"

        # The metadata goes on a copy: written into the stored graph, which is the caller's ModelProto, one call's keys
        # would reach every later export.
        op = onnx.ModelProto()
        op.CopyFrom(self._combined_op if include_pre_and_post_processor else self.model)
        self._add_metadata(op, additional_metadata)
        if save:
            self._export(op, onnx_name, **kwargs)
        return op
