"""Timestamp helpers for recorder event streams."""

from __future__ import annotations

from datetime import datetime
import re


_TIMESTAMP_RE = re.compile(
    r"^(?P<head>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})"
    r"(?:\.(?P<fraction>\d+))?"
    r"(?P<offset>Z|[+-]\d{2}:\d{2})$"
)


def parse_timestamp(value: str) -> datetime:
    """Parse recorder timestamps, including nanosecond precision."""
    match = _TIMESTAMP_RE.match(value)
    if not match:
        return datetime.fromisoformat(value.replace("Z", "+00:00"))

    fraction = match.group("fraction") or ""
    if fraction:
        fraction = fraction[:6].ljust(6, "0")

    offset = "+00:00" if match.group("offset") == "Z" else match.group("offset")
    normalized = match.group("head")
    if fraction:
        normalized = f"{normalized}.{fraction}"

    return datetime.fromisoformat(f"{normalized}{offset}")
