from pathlib import Path

from pydantic_ai.messages import ModelMessage, ModelMessagesTypeAdapter


def load_history(history_path: Path) -> list[ModelMessage]:
    if not history_path.exists():
        return []

    try:
        raw = history_path.read_bytes()
        return ModelMessagesTypeAdapter.validate_json(raw) if raw else []
    except Exception:
        return []


def save_history(history_path: Path, messages: list[ModelMessage]) -> None:
    history_path.parent.mkdir(parents=True, exist_ok=True)
    history_path.write_bytes(ModelMessagesTypeAdapter.dump_json(messages))
