"""HandlerContext — immutable bundle of model callbacks shared by all handlers."""
from __future__ import annotations

import time
from dataclasses import dataclass, field

from ._types import (
    EmbedFn,
    InferFn,
    InferImageEditFn,
    InferImageFn,
    InferStreamFn,
    SynthesizeFn,
    TranscribeFn,
)


@dataclass(frozen=True)
class HandlerContext:
    model_id: str
    default_max_tokens: int
    category: str = "text-generation"
    infer: InferFn | None = None
    infer_stream: InferStreamFn | None = None
    embed: EmbedFn | None = None
    infer_image: InferImageFn | None = None
    infer_image_edit: InferImageEditFn | None = None
    transcribe: TranscribeFn | None = None
    synthesize: SynthesizeFn | None = None
    created: int = field(default_factory=lambda: int(time.time()))
    metadata: dict = field(default_factory=dict)

    @property
    def model_obj(self) -> dict:
        m = self.metadata
        obj: dict = {
            "id": self.model_id,
            "object": "model",
            "created": self.created,
            "owned_by": "llmpm",
            "category": self.category,
        }
        # registry metadata (all optional — only present when served via serve_cmd)
        model_type = m.get("model_type")
        if model_type:
            obj["backend"] = "llama.cpp" if model_type == "gguf" else "transformers"
        for key in ("path", "primary_file", "files", "size_bytes", "installed_at", "tags"):
            if m.get(key) is not None:
                obj[key] = m[key]
        return obj
