"""Tests for utility functions."""

import json

from langchain_core.outputs import Generation

from langchain_hana_cache.utils import (
    deserialize_generations,
    hash_prompt,
    serialize_generations,
)


class TestHashPrompt:
    def test_deterministic(self):
        h1 = hash_prompt("hello world")
        h2 = hash_prompt("hello world")
        assert h1 == h2

    def test_different_inputs_different_hashes(self):
        h1 = hash_prompt("hello")
        h2 = hash_prompt("world")
        assert h1 != h2

    def test_returns_64_char_hex(self):
        h = hash_prompt("test")
        assert len(h) == 64
        assert all(c in "0123456789abcdef" for c in h)

    def test_unicode_prompt(self):
        h = hash_prompt("información según diseño")
        assert len(h) == 64

    def test_empty_string(self):
        h = hash_prompt("")
        assert len(h) == 64


class TestSerialization:
    def test_roundtrip_single_generation(self):
        gens = [Generation(text="Hello, world!")]
        serialized = serialize_generations(gens)
        result = deserialize_generations(serialized)
        assert len(result) == 1
        assert result[0].text == "Hello, world!"

    def test_roundtrip_multiple_generations(self):
        gens = [
            Generation(text="First response"),
            Generation(text="Second response"),
        ]
        serialized = serialize_generations(gens)
        result = deserialize_generations(serialized)
        assert len(result) == 2
        assert result[0].text == "First response"
        assert result[1].text == "Second response"

    def test_roundtrip_with_generation_info(self):
        gens = [Generation(text="Hello", generation_info={"finish_reason": "stop"})]
        serialized = serialize_generations(gens)
        result = deserialize_generations(serialized)
        assert result[0].generation_info == {"finish_reason": "stop"}

    def test_roundtrip_without_generation_info(self):
        gens = [Generation(text="Hello")]
        serialized = serialize_generations(gens)
        result = deserialize_generations(serialized)
        assert result[0].generation_info is None

    def test_serialized_format_is_json(self):
        gens = [Generation(text="test")]
        serialized = serialize_generations(gens)
        parsed = json.loads(serialized)
        assert isinstance(parsed, list)
        assert parsed[0]["text"] == "test"

    def test_empty_list(self):
        serialized = serialize_generations([])
        result = deserialize_generations(serialized)
        assert result == []
