"""Tests for the feed system."""

import time

import pytest

from horizon._horizon import Engine, FeedSnapshot, RiskConfig


class TestFeedSnapshot:
    def test_create_snapshot(self):
        snap = FeedSnapshot(price=100.5, source="test")
        assert abs(snap.price - 100.5) < 1e-10
        assert snap.source == "test"
        assert abs(snap.bid) < 1e-10
        assert abs(snap.ask) < 1e-10

    def test_snapshot_defaults(self):
        snap = FeedSnapshot()
        assert abs(snap.price) < 1e-10
        assert snap.source == ""

    def test_snapshot_repr(self):
        snap = FeedSnapshot(price=50000.0, source="binance:btcusdt", bid=49999.0, ask=50001.0)
        r = repr(snap)
        assert "50000" in r
        assert "binance" in r


class TestEngineFeedManager:
    def test_feed_snapshot_none_before_start(self):
        engine = Engine()
        assert engine.feed_snapshot("btc") is None

    def test_all_feed_snapshots_empty(self):
        engine = Engine()
        assert engine.all_feed_snapshots() == {}

    def test_start_feed_creates_snapshot(self):
        engine = Engine()
        engine.start_feed("btc", "binance_ws", symbol="btcusdt")
        # Give the feed manager time to initialize the snapshot
        time.sleep(0.1)
        snap = engine.feed_snapshot("btc")
        assert snap is not None
        # Initially price is 0.0 (no data received yet from WebSocket)
        assert isinstance(snap.price, float)

    def test_start_multiple_feeds(self):
        engine = Engine()
        engine.start_feed("btc", "binance_ws", symbol="btcusdt")
        engine.start_feed("eth", "binance_ws", symbol="ethusdt")
        time.sleep(0.1)
        snaps = engine.all_feed_snapshots()
        assert "btc" in snaps
        assert "eth" in snaps

    def test_stop_feeds(self):
        engine = Engine()
        engine.start_feed("btc", "binance_ws", symbol="btcusdt")
        engine.stop_feeds()
        # Should not crash

    def test_unknown_feed_type_raises(self):
        engine = Engine()
        with pytest.raises(ValueError, match="unknown feed type"):
            engine.start_feed("test", "invalid_type")
