"""Custom endpoint handler for HF Inference Endpoints.

Bypasses the default huggingface_inference_toolkit auto-pipeline (which was
crashing at model-load on this Qwen2.5-Coder merge). Loads explicitly in bf16,
handles both plain-string and chat-message inputs, returns the generated text
in the shape the MCP client expects: [{"generated_text": "..."}].
"""
from __future__ import annotations

from typing import Any

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer


class EndpointHandler:
    def __init__(self, path: str = ""):
        print(f"[handler] Loading tokenizer from {path}")
        self.tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
        if self.tokenizer.pad_token is None:
            self.tokenizer.pad_token = self.tokenizer.eos_token

        print(f"[handler] Loading model from {path} in bfloat16")
        self.model = AutoModelForCausalLM.from_pretrained(
            path,
            torch_dtype=torch.bfloat16,
            device_map="auto",
            trust_remote_code=True,
        )
        self.model.eval()
        print("[handler] Ready")

    def __call__(self, data: dict[str, Any]) -> list[dict[str, str]]:
        inputs = data.get("inputs", "")
        params = data.get("parameters", {}) or {}

        max_new_tokens = int(params.get("max_new_tokens", 1500))
        temperature = float(params.get("temperature", 0.1))
        top_p = float(params.get("top_p", 0.95))
        do_sample = bool(params.get("do_sample", temperature > 0.01))
        return_full_text = bool(params.get("return_full_text", False))

        # Accept either a plain string or a list of chat messages.
        if isinstance(inputs, list) and inputs and isinstance(inputs[0], dict):
            prompt_text = self.tokenizer.apply_chat_template(
                inputs, tokenize=False, add_generation_prompt=True
            )
        else:
            prompt_text = inputs

        tokenized = self.tokenizer(
            prompt_text,
            return_tensors="pt",
            truncation=True,
            max_length=8192,
        ).to(self.model.device)

        with torch.no_grad():
            outputs = self.model.generate(
                **tokenized,
                max_new_tokens=max_new_tokens,
                temperature=temperature if do_sample else 1.0,
                top_p=top_p,
                do_sample=do_sample,
                pad_token_id=self.tokenizer.eos_token_id,
                eos_token_id=self.tokenizer.eos_token_id,
            )

        prompt_len = tokenized["input_ids"].shape[-1]
        new_tokens = outputs[0] if return_full_text else outputs[0][prompt_len:]
        text = self.tokenizer.decode(new_tokens, skip_special_tokens=True)

        return [{"generated_text": text}]
