from .imports import (
    pipeline,
    AutoTokenizer,
    AutoModelForSeq2SeqLM,
    torch,
    DEFAULT_PATHS,
    SingletonMeta,
    Optional
    )


def _coerce_optional(value, default):
    """
    Return `default` when `value` is None (or the integer/string zero).
    FIX: original logic was inverted — it replaced truthy values with default,
    leaving zero/None to pass through unchanged.
    """
    if value is None or value in (0, 0.0, "0"):
        return default
    return value


class FlanManager(metaclass=SingletonMeta):
    def __init__(self):
        if not hasattr(self, "initialized"):
            self.initialized = True
            self.MODEL_NAME: str = DEFAULT_PATHS["flan"]
            self.tokenizer = AutoTokenizer.from_pretrained(self.MODEL_NAME)
            self.model = AutoModelForSeq2SeqLM.from_pretrained(self.MODEL_NAME)
            self.device = 0 if torch.cuda.is_available() else -1
            self.summarizer = pipeline(
                "text2text-generation",
                model=self.model,
                tokenizer=self.tokenizer,
                device=self.device,
            )

    def get_flan_summary(
        self,
        text: str,
        max_chunk: Optional[int] = None,
        min_length: Optional[int] = None,
        max_length: Optional[int] = None,
        do_sample: Optional[bool] = None,
    ) -> str:
        prompt = f"""
You are a highly observant assistant tasked with summarizing long, unscripted video monologues.

TEXT:
{text}

INSTRUCTIONS:
Summarize the speaker's core points and tone as if describing the monologue to someone who hasn't heard it.
Group related ideas together. Highlight interesting or unusual claims. Use descriptive language.
Output a full narrative paragraph (or two), not bullet points.
"""
        # FIX: _coerce_optional replaces the inverted zero_or_default
        max_chunk = _coerce_optional(max_chunk, 512)
        min_length = _coerce_optional(min_length, 100)
        max_length = _coerce_optional(max_length, 512)
        do_sample = do_sample if do_sample is not None else False

        return self.summarizer(
            prompt,
            max_length=max_length,
            min_length=min_length,
            do_sample=do_sample,
        )[0]["generated_text"]


def get_flan_manager() -> FlanManager:
    return FlanManager()


def get_flan_summary(
    text: str,
    max_chunk: Optional[int] = None,
    min_length: Optional[int] = None,
    max_length: Optional[int] = None,
    do_sample: Optional[bool] = None,
) -> str:
    return get_flan_manager().get_flan_summary(
        text=text,
        max_chunk=max_chunk,
        min_length=min_length,
        max_length=max_length,
        do_sample=do_sample,
    )
