"""src.live.bars — detection condivisa della barra in formazione (lezione EXIT-16)."""
import numpy as np

from src.live.bars import bar_ms_of, last_bar_is_forming, last_settled_idx

H = 3_600_000


def _ts(n, end_ms):
    return np.arange(end_ms - (n - 1) * H, end_ms + 1, H, dtype="int64")


def test_bar_ms_median():
    assert bar_ms_of(_ts(50, 10 * H)) == H
    assert bar_ms_of([1]) == 0                      # troppo corta per stimare


def test_forming_vs_settled():
    now = 1_000_000 * H
    ts = _ts(60, now)                                # ultima barra appena aperta
    assert last_bar_is_forming(ts, now_ms=now + 1)   # in corso
    assert last_settled_idx(ts, now_ms=now + 1) == -2
    assert not last_bar_is_forming(ts, now_ms=now + H)   # durata trascorsa
    assert last_settled_idx(ts, now_ms=now + H) == -1


def test_degenerate_series_defaults_to_settled():
    assert not last_bar_is_forming([], now_ms=0)
    assert last_settled_idx([123], now_ms=0) == -1   # bar_ms non stimabile -> -1
