from __future__ import annotations

import datetime
from contextlib import aclosing

from pytz import UTC

from asyncvictoria import DS, Entry
from asyncvictoria.mock import VictoriaTester


async def test_basic(free_tcp_port_factory):
    async with VictoriaTester(free_tcp_port_factory(),free_tcp_port_factory()).run() as tc:
        e = Entry(
            series="test_A",
            time=1500000000,
            value=123,
            tags={"foo": "one"},
            mode=DS.gauge,
        )
        await tc.put(e)
        await tc.flush()  # Ensure data is flushed
        await tc.force_flush()  # Force VictoriaMetrics to flush all pending data
        n = 0
        # Use a smaller time range around the data point to avoid exceeding point limits
        # Try querying without tag filter first
        gd = tc.get_data("test_A", tags={}, t_start=1499999000, t_end=1500001000)
        async with aclosing(gd):
            async for x in gd:
                n += 1
                assert x.value == 123
                # VictoriaMetrics may align timestamps to step boundaries
                # Allow for some timestamp drift
                assert abs(x.time - 1500000000) < 60, f"Expected ~1500000000, got {x.time}"
                # Check the date is approximately correct (within 1 minute)
                expected_date = datetime.datetime(2017, 7, 14, 2, 40, tzinfo=UTC)
                assert abs((x.date - expected_date).total_seconds()) < 60
        assert n == 1
