"""Utility functions for hashing and serialization."""

from __future__ import annotations

import hashlib
import json
from typing import Any

from langchain_core.outputs import Generation


def hash_prompt(prompt: str) -> str:
    """Return SHA-256 hex digest of a prompt string."""
    return hashlib.sha256(prompt.encode("utf-8")).hexdigest()


def serialize_generations(generations: list[Generation]) -> str:
    """Serialize a list of Generation objects to a JSON string."""
    return json.dumps([generation_to_dict(g) for g in generations])


def deserialize_generations(data: str) -> list[Generation]:
    """Deserialize a JSON string back to a list of Generation objects."""
    items = json.loads(data)
    return [dict_to_generation(d) for d in items]


def generation_to_dict(gen: Generation) -> dict[str, Any]:
    """Convert a Generation to a serializable dict."""
    d: dict[str, Any] = {"text": gen.text}
    if gen.generation_info:
        d["generation_info"] = gen.generation_info
    return d


def dict_to_generation(d: dict[str, Any]) -> Generation:
    """Convert a dict back to a Generation."""
    return Generation(
        text=d["text"],
        generation_info=d.get("generation_info"),
    )
