"""NTP clock-offset helpers, same math as Listen/Take Stamp (`listento/lock.py`).

Client sends t1, server stamps t2 (recv) and t3 (send), client stamps t4.
theta is the offset such that server_clock ≈ client_clock + theta.
We keep the theta from the lowest-RTT sample (NTP best practice).
"""
from __future__ import annotations


def now_us() -> int:
    import time
    return int(time.time() * 1e6)


def ntp_offset_us(t1: int, t2: int, t3: int, t4: int) -> int:
    """Offset such that server_clock ≈ client_clock + theta."""
    return ((t2 - t1) + (t3 - t4)) // 2


def ntp_rtt_us(t1: int, t2: int, t3: int, t4: int) -> int:
    return (t4 - t1) - (t3 - t2)


class MinRttClock:
    """Keep the clock offset from the lowest-RTT sync."""

    def __init__(self, keep: int = 16):
        self.samples: list[tuple[int, int]] = []  # (rtt, theta)
        self.keep = keep

    def add(self, t1, t2, t3, t4) -> tuple[int, int]:
        rtt = ntp_rtt_us(t1, t2, t3, t4)
        th = ntp_offset_us(t1, t2, t3, t4)
        if rtt < 0:
            return self.theta(), rtt
        self.samples.append((rtt, th))
        self.samples.sort()
        self.samples = self.samples[: self.keep]
        return self.theta(), rtt

    def theta(self) -> int:
        return self.samples[0][1] if self.samples else 0

    def best_rtt(self) -> int | None:
        return self.samples[0][0] if self.samples else None
