"""Question Answering predictive task."""

from __future__ import annotations

from collections.abc import Callable, 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_, langchain_, outlines_
from sieves.engines.types import GenerationSettings
from sieves.serialization import Config
from sieves.tasks.distillation.types import DistillationFramework
from sieves.tasks.predictive.core import FewshotExample as BaseFewshotExample
from sieves.tasks.predictive.core import PredictiveTask
from sieves.tasks.predictive.question_answering.bridges import (
    DSPyQA,
    LangChainQA,
    OutlinesQA,
)

_TaskModel = dspy_.Model | langchain_.Model | outlines_.Model
_TaskPromptSignature = pydantic.BaseModel | dspy_.PromptSignature
_TaskResult = pydantic.BaseModel | dspy_.Result
_TaskBridge = DSPyQA | LangChainQA | OutlinesQA


class FewshotExample(BaseFewshotExample):
    """Few-shot example with questions and answers for a context."""

    questions: tuple[str, ...] | list[str]
    answers: tuple[str, ...] | list[str]

    @override
    @property
    def input_fields(self) -> Sequence[str]:
        return "text", "questions"

    @override
    @property
    def target_fields(self) -> Sequence[str]:
        return ("answers",)


class QuestionAnswering(PredictiveTask[_TaskPromptSignature, _TaskResult, _TaskBridge]):
    """Answer questions about a text using structured engines."""

    def __init__(
        self,
        questions: list[str],
        model: _TaskModel,
        task_id: str | None = None,
        include_meta: bool = True,
        batch_size: int = -1,
        prompt_instructions: str | None = None,
        fewshot_examples: Sequence[FewshotExample] = (),
        generation_settings: GenerationSettings = GenerationSettings(),
        condition: Callable[[Doc], bool] | None = None,
    ) -> None:
        """
        Initialize QuestionAnswering task.

        :param questions: Questions to answer.
        :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 prompt_instructions: Custom prompt instructions. If None, default instructions are used.
        :param fewshot_examples: Few-shot examples.
        :param generation_settings: Settings for structured generation.
        :param condition: Optional callable that determines whether to process each document.
        """
        self._questions = questions
        super().__init__(
            model=model,
            task_id=task_id,
            include_meta=include_meta,
            batch_size=batch_size,
            overwrite=False,
            prompt_instructions=prompt_instructions,
            fewshot_examples=fewshot_examples,
            generation_settings=generation_settings,
            condition=condition,
        )
        self._fewshot_examples: Sequence[FewshotExample]

    @override
    def _init_bridge(self, engine_type: EngineType) -> _TaskBridge:
        bridge_types: dict[EngineType, type[_TaskBridge]] = {
            EngineType.dspy: DSPyQA,
            EngineType.outlines: OutlinesQA,
            EngineType.langchain: LangChainQA,
        }

        try:
            bridge_type = bridge_types[engine_type]

            return bridge_type(
                task_id=self._task_id,
                prompt_instructions=self._custom_prompt_instructions,
                questions=self._questions,
                generation_settings=self._generation_settings,
            )
        except KeyError as err:
            raise KeyError(f"Engine type {engine_type} is not supported by {self.__class__.__name__}.") from err

    @staticmethod
    @override
    def supports() -> set[EngineType]:
        return {
            EngineType.dspy,
            EngineType.langchain,
            EngineType.outlines,
        }

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

    @override
    def to_hf_dataset(self, docs: Iterable[Doc], threshold: float = 0.5) -> datasets.Dataset:
        # Define metadata.
        features = datasets.Features(
            {"text": datasets.Value("string"), "answers": datasets.Sequence(datasets.Value("string"))}
        )
        info = datasets.DatasetInfo(
            description=f"Question-answering dataset with questions {self._questions}. Generated with sieves "
            f"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, answers in data:
                yield {"text": text, "answers": answers}

        # 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
