# retoor <retoor@molodetz.nl>

from __future__ import annotations

from typing import Any


def _repair_history(messages: list[dict[str, Any]]) -> None:
    last_idx = None
    for i in range(len(messages) - 1, -1, -1):
        message = messages[i]
        if message.get("role") == "assistant" and message.get("tool_calls"):
            last_idx = i
            break
    if last_idx is None:
        while messages and messages[-1].get("role") == "tool":
            messages.pop()
        return
    declared = {
        call.get("id")
        for call in (messages[last_idx].get("tool_calls") or [])
        if call.get("id")
    }
    answered = {
        messages[j].get("tool_call_id")
        for j in range(last_idx + 1, len(messages))
        if messages[j].get("role") == "tool"
    }
    if not declared or not declared.issubset(answered):
        del messages[last_idx:]


def _now_iso() -> str:
    from datetime import datetime, timezone

    return datetime.now(timezone.utc).isoformat()


def _format_offset(offset: Any) -> str:
    if offset is None:
        return "+00:00"
    total_minutes = int(offset.total_seconds() // 60)
    sign = "+" if total_minutes >= 0 else "-"
    total_minutes = abs(total_minutes)
    return f"{sign}{total_minutes // 60:02d}:{total_minutes % 60:02d}"
