"""Text summarization predictive task."""

from __future__ import annotations

from collections.abc import Iterable, Sequence
from pathlib import Path
from typing import Any, override

import datasets
import pydantic

from sieves.data import Doc
from sieves.engines import EngineType, dspy_, glix_, instructor_, langchain_, ollama_, outlines_, vllm_
from sieves.engines.types import GenerationSettings
from sieves.serialization import Config
from sieves.tasks.postprocessing.distillation.types import DistillationFramework
from sieves.tasks.predictive.bridges import GliXBridge
from sieves.tasks.predictive.core import PredictiveTask
from sieves.tasks.predictive.summarization.bridges import (
    DSPySummarization,
    InstructorSummarization,
    LangChainSummarization,
    OllamaSummarization,
    OutlinesSummarization,
    VLLMSummarization,
)

_TaskModel = (
    dspy_.Model | glix_.Model | instructor_.Model | langchain_.Model | ollama_.Model | outlines_.Model | vllm_.Model
)
_TaskPromptSignature = pydantic.BaseModel | dspy_.PromptSignature | glix_.PromptSignature | vllm_.Result
_TaskResult = outlines_.Result | dspy_.Result | ollama_.Result | vllm_.Result
_TaskBridge = (
    DSPySummarization
    | GliXBridge
    | InstructorSummarization
    | LangChainSummarization
    | OutlinesSummarization
    | OllamaSummarization
    | VLLMSummarization
)


class FewshotExample(pydantic.BaseModel):
    """Few-shot example with a target summary."""

    text: str
    n_words: int
    summary: str


class Summarization(PredictiveTask[_TaskPromptSignature, _TaskResult, _TaskBridge]):
    """Summarize documents to a target length using structured engines."""

    def __init__(
        self,
        n_words: int,
        model: _TaskModel,
        task_id: str | None = None,
        include_meta: bool = True,
        batch_size: int = -1,
        overwrite: bool = False,
        prompt_template: str | None = None,
        prompt_signature_desc: str | None = None,
        fewshot_examples: Iterable[FewshotExample] = (),
        generation_settings: GenerationSettings = GenerationSettings(),
    ) -> None:
        """Initialize new Summarization task.

        :param n_words: Maximal number of words (consider this a guideline, not a strict limit).
        :param model: Model to use.
        :param task_id: Task ID.
        :param include_meta: Whether to include meta information generated by the task.
        :param batch_size: Batch size to use for inference. Use -1 to process all documents at once.
        :param overwrite: Some tasks, e.g. anonymization or translation, output a modified version of the input text.
            If True, these tasks overwrite the original document text. If False, the result will just be stored in the
            documents' `.results` field.
        :param prompt_template: Custom prompt template. If None, task's default template is being used.
        :param prompt_signature_desc: Custom prompt signature description. If None, default will be used.
        :param fewshot_examples: Few-shot examples.
        :param generation_settings: Settings for structured generation.
        """
        self._n_words = n_words

        super().__init__(
            model=model,
            task_id=task_id,
            include_meta=include_meta,
            batch_size=batch_size,
            overwrite=overwrite,
            prompt_template=prompt_template,
            prompt_signature_desc=prompt_signature_desc,
            fewshot_examples=fewshot_examples,
            generation_settings=generation_settings,
        )

    @override
    def _init_bridge(self, engine_type: EngineType) -> _TaskBridge:
        if engine_type == EngineType.glix:
            return GliXBridge(
                task_id=self._task_id,
                prompt_template=self._custom_prompt_template,
                prompt_signature_desc=self._custom_prompt_signature_desc,
                prompt_signature=[],
                inference_mode=glix_.InferenceMode.summarization,
            )

        bridge_types: dict[EngineType, type[_TaskBridge]] = {
            EngineType.dspy: DSPySummarization,
            EngineType.instructor: InstructorSummarization,
            EngineType.langchain: LangChainSummarization,
            EngineType.outlines: OutlinesSummarization,
            EngineType.ollama: OllamaSummarization,
            EngineType.vllm: VLLMSummarization,
        }

        try:
            bridge_type = bridge_types[engine_type]
            assert not issubclass(bridge_type, GliXBridge)

            return bridge_type(
                task_id=self._task_id,
                prompt_template=self._custom_prompt_template,
                prompt_signature_desc=self._custom_prompt_signature_desc,
                overwrite=self._overwrite,
                n_words=self._n_words,
            )
        except KeyError as err:
            raise KeyError(f"Engine type {engine_type} is not supported by {self.__class__.__name__}.") from err

    @property
    @override
    def supports(self) -> set[EngineType]:
        return {
            EngineType.dspy,
            EngineType.glix,
            EngineType.instructor,
            EngineType.ollama,
            EngineType.outlines,
            EngineType.vllm,
        }

    @property
    @override
    def _state(self) -> dict[str, Any]:
        return {
            **super()._state,
            "n_words": self._n_words,
        }

    @override
    def to_hf_dataset(self, docs: Iterable[Doc], threshold: float = 0.5) -> datasets.Dataset:
        # Define metadata.
        features = datasets.Features({"text": datasets.Value("string"), "summary": datasets.Value("string")})
        info = datasets.DatasetInfo(
            description=f"Summarization dataset. Generated with sieves v{Config.get_version()}.",
            features=features,
        )

        # Fetch data used for generating dataset.
        try:
            data = [(doc.text, doc.results[self._task_id]) for doc in docs]
        except KeyError as err:
            raise KeyError(f"Not all documents have results for this task with ID {self._task_id}") from err

        def generate_data() -> Iterable[dict[str, Any]]:
            """Yield results as dicts.

            :return: Results as dicts.
            """
            for text, summary in data:
                yield {"text": text, "summary": summary}

        # Create dataset.
        return datasets.Dataset.from_generator(generate_data, features=features, info=info)

    @override
    def distill(
        self,
        base_model_id: str,
        framework: DistillationFramework,
        data: datasets.Dataset | Sequence[Doc],
        output_path: Path | str,
        val_frac: float,
        init_kwargs: dict[str, Any] | None = None,
        train_kwargs: dict[str, Any] | None = None,
        seed: int | None = None,
    ) -> None:
        raise NotImplementedError
