# Copyright 2025 The MelowRAG Author @erfanzar (Erfan Zare Chavoshi).
#
# 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
#
#     https://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.

"""
Summary module
"""

import re

from ..hfpipeline import HFPipeline


class Summary(HFPipeline):
    """
    Summarizes text.
    """

    def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
        super().__init__("summarization", path, quantize, gpu, model, **kwargs)

    def __call__(self, text, minlength=None, maxlength=None, workers=0):
        """
        Runs a summarization model against a block of text.

        This method supports text as a string or a list. If the input is a string, the return
        type is text. If text is a list, a list of text is returned with a row per block of text.

        Args:
            text: text|list
            minlength: minimum length for summary
            maxlength: maximum length for summary
            workers: number of concurrent workers to use for processing data, defaults to None

        Returns:
            summary text
        """

        check = maxlength if maxlength else self.maxlength()

        texts = text if isinstance(text, list) else [text]
        params = [(x, text if len(text) >= check else None) for x, text in enumerate(texts)]

        kwargs = self.args(minlength, maxlength)

        inputs = [text for _, text in params if text]
        if inputs:
            results = self.pipeline(inputs, num_workers=workers, **kwargs)

            results = iter([self.clean(x["summary_text"]) for x in results])
            results = [next(results) if text else texts[x] for x, text in params]
        else:
            results = texts

        return results[0] if isinstance(text, str) else results

    def clean(self, text):
        """
        Applies a series of rules to clean extracted text.

        Args:
            text: input text

        Returns:
            clean text
        """

        text = re.sub(r"\s*\.\s*", ". ", text)
        text = text.strip()

        return text

    def args(self, minlength, maxlength):
        """
        Builds keyword arguments.

        Args:
            minlength: minimum length for summary
            maxlength: maximum length for summary

        Returns:
            keyword arguments
        """

        kwargs = {"truncation": True}
        if minlength:
            kwargs["min_length"] = minlength
        if maxlength:
            kwargs["max_length"] = maxlength
            kwargs["max_new_tokens"] = None

            if "min_length" not in kwargs or kwargs["min_length"] > kwargs["max_length"]:
                kwargs["min_length"] = kwargs["max_length"]

        return kwargs
