"""Session record construction, serialization, and index entry building."""

from __future__ import annotations

import uuid
from datetime import UTC, datetime
from typing import Any

import msgspec.json

from alice_cli.models import IndexEntry, SessionRecord, TokenUsage


def build_session_record(
    *,
    record_type: str,
    model: str,
    prompt: str,
    response: str | None,
    tokens: TokenUsage,
    metadata: dict[str, Any] | None = None,
) -> SessionRecord:
    """Create a SessionRecord with generated UUID4 id and UTC ISO 8601 timestamp."""
    return SessionRecord(
        id=str(uuid.uuid4()),
        type=record_type,
        timestamp=datetime.now(UTC).isoformat(),
        model=model,
        prompt=prompt,
        response=response,
        tokens=tokens,
        metadata=metadata,
    )


def serialize_record(record: SessionRecord) -> str:
    """Serialize to JSON string (UTF-8). None fields become null."""
    data: dict[str, Any] = {
        "id": record.id,
        "type": record.type,
        "timestamp": record.timestamp,
        "model": record.model,
        "prompt": record.prompt,
        "response": record.response,
        "tokens": (
            {
                "input": record.tokens.input,
                "output": record.tokens.output,
                "total": record.tokens.total,
            }
            if record.tokens is not None
            else None
        ),
        "metadata": record.metadata,
    }
    return msgspec.json.encode(data).decode("utf-8")  # type: ignore[no-any-return,unused-ignore]


def deserialize_record(json_str: str) -> SessionRecord:
    """Parse JSON string back to SessionRecord."""
    data: dict[str, Any] = msgspec.json.decode(json_str.encode("utf-8"))
    tokens_raw = data.get("tokens")
    tokens = (
        TokenUsage(
            input=tokens_raw["input"], output=tokens_raw["output"], total=tokens_raw["total"]
        )
        if tokens_raw is not None
        else None
    )
    return SessionRecord(
        id=data["id"],
        type=data["type"],
        timestamp=data["timestamp"],
        model=data["model"],
        prompt=data["prompt"],
        response=data.get("response"),
        tokens=tokens,
        metadata=data.get("metadata"),
    )


def build_index_entry(record: SessionRecord) -> IndexEntry:
    """Extract index metadata from a full SessionRecord."""
    return IndexEntry(
        id=record.id,
        type=record.type,
        timestamp=record.timestamp,
        model=record.model,
        prompt_preview=record.prompt[:80],
        tokens=record.tokens,
    )
