import functools
from pathlib import Path
from typing import Any

from ..decision import DecisionConfig, label_token_ids
from ..utils import add_end_docstrings, is_torch_available
from .base import Pipeline, build_pipeline_init_args


if is_torch_available():
    from ..decision.modeling_utils import DecisionMixin, process_scores


@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
class DecisionPipeline(Pipeline):
    """
    Decision pipeline: answers typed questions (`choice`, `score`, `noul`) about a `state` with a probability for every
    option, from one forward pass per prompt (the System One API of Jev-like models). The decision config (see
    [`DecisionConfig`]) lives next to the model or in the repo given as `decision_config`. A decision model
    (`XxxForDecision`) scores the options itself; any other model scores them by the next-token logits of their labels, so any chat model can answer.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> decide = pipeline("decision", model="Qwen/Qwen2.5-0.5B-Instruct")
    >>> answers = decide(
    ...     {
    ...         "state": "I was charged twice for my order and want a refund.",
    ...         "questions": {"refund": {"type": "noul", "instructions": "Is a refund requested?"}},
    ...     }
    ... )
    >>> answers["refund"]["type"]
    'noul'
    ```

    Call arguments:
        inputs (`dict`, `str` or `list`):
            `{"state": ..., "questions": {name: {"type": ..., "instructions": ..., "criteria": ...}}}` or its JSON, with
            `type` one of `choice` (`criteria` maps options to descriptions), `score` (`criteria` lists the levels,
            lowest first) or `noul` (optional `criteria` describe `true` and `false`). Requests can carry `assets`, as
            in the System One API.
        questions (`dict`, *optional*):
            Questions to ask the input, as the `state` of a request.
        assets (`dict`, *optional*):
            Images keyed by a placeholder: wherever the placeholder appears in a string of the state, the instructions
            or the criteria, the model sees the image. An image is a System One asset (`{"type": "image", "format":
            "png", "data_base64": ...}`), a PIL image, a path or a URL. Needs a model with a processor that handles
            images.

    Returns `dict` (or a list of `dict`): the answers keyed by question name, in the System One format.
    """

    _load_image_processor = False
    _load_feature_extractor = False
    _load_tokenizer = True

    def __init__(
        self,
        *args,
        decision_config: DecisionConfig | str | None = None,
        **kwargs,
    ):
        super().__init__(*args, **kwargs)
        repo = decision_config if isinstance(decision_config, (str, Path)) else self.model.name_or_path
        if not isinstance(decision_config, DecisionConfig):
            # The one of a decision model (`XxxForDecision`), which scores the options itself; any other model scores
            # them by the logits of their labels
            use_model = isinstance(self.model, DecisionMixin) and decision_config is None
            decision_config = self.model.decision_config if use_model else DecisionConfig.from_pretrained(repo)
        self.decision_config = decision_config
        if self.decision_config.adapter:  # a LoRA in a subfolder of the repo
            self.model.load_adapter(repo, adapter_kwargs={"subfolder": self.decision_config.adapter})
        self.label_token_ids = functools.cache(functools.partial(label_token_ids, self.tokenizer))

    def _sanitize_parameters(self):
        return {}, {}, {}

    def preprocess(self, request: dict[str, Any] | str):
        return {"prompts": self.decision_config.prepare_inputs(request, self.processor or self.tokenizer)}

    def _forward(self, model_inputs):
        # TODO: batch / continious batching
        model, decision_config, prompts = self.model, self.decision_config, model_inputs["prompts"]
        if isinstance(model, DecisionMixin):
            scores = [
                model.decide(**inputs, decision_questions=q, decision_config=decision_config) for inputs, q in prompts
            ]
            return {"prompts": prompts, "scores": scores}
        scores = []
        for inputs, questions in prompts:  # the logits of the labels before each mark
            inputs = dict(inputs)
            marks = inputs.pop("marks")
            logits = model(**inputs, use_cache=False, logits_to_keep=marks - 1).logits[0]
            labels = [logits[i, self.label_token_ids(tuple(q.labels))] for i, q in enumerate(questions)]
            scores.append(process_scores(decision_config, inputs["input_ids"], marks, questions, labels))
        return {"prompts": prompts, "scores": scores}

    def postprocess(self, model_outputs):
        answers = {}
        for (_, questions), scores in zip(model_outputs["prompts"], model_outputs["scores"]):
            answers |= {q.name: q.answer(s.softmax(-1).tolist()) for q, s in zip(questions, scores)}
        return answers
