"""Tests for historical tick storage (feed_ticks table)."""

import os
import tempfile
import time

import pytest
from horizon._horizon import Engine, RiskConfig


@pytest.fixture
def engine_with_db():
    """Engine with a temp database for tick storage tests."""
    fd, path = tempfile.mkstemp(suffix=".db")
    os.close(fd)
    engine = Engine(risk_config=RiskConfig(), db_path=path)
    yield engine, path
    try:
        os.unlink(path)
    except OSError:
        pass


class TestTickRecording:
    def test_record_tick_no_feed_returns_false(self, engine_with_db):
        engine, _ = engine_with_db
        assert engine.record_tick("nonexistent", "mkt1") is False

    def test_tick_count_empty(self, engine_with_db):
        engine, _ = engine_with_db
        assert engine.tick_count("feed1") == 0

    def test_query_ticks_empty(self, engine_with_db):
        engine, _ = engine_with_db
        result = engine.query_ticks("feed1", 0.0, 9999999999.0, 100)
        assert result == []

    def test_purge_old_ticks_empty(self, engine_with_db):
        engine, _ = engine_with_db
        assert engine.purge_old_ticks(3600.0) == 0


class TestTickRecordingNoPersistence:
    def test_record_tick_no_db(self):
        engine = Engine()
        assert engine.record_tick("feed1", "mkt1") is False

    def test_tick_count_no_db(self):
        engine = Engine()
        assert engine.tick_count("feed1") == 0

    def test_query_ticks_no_db(self):
        engine = Engine()
        result = engine.query_ticks("feed1", 0.0, 9999999999.0, 100)
        assert result == []

    def test_purge_no_db(self):
        engine = Engine()
        assert engine.purge_old_ticks(3600.0) == 0


class TestTickQueryParams:
    def test_query_with_zero_limit(self, engine_with_db):
        engine, _ = engine_with_db
        result = engine.query_ticks("feed1", 0.0, 9999999999.0, 0)
        assert result == []

    def test_query_large_time_range(self, engine_with_db):
        engine, _ = engine_with_db
        result = engine.query_ticks("feed1", 0.0, 99999999999.0, 10000)
        assert result == []

    def test_purge_with_large_age(self, engine_with_db):
        engine, _ = engine_with_db
        assert engine.purge_old_ticks(999999.0) == 0
