import json

import httpx
import pytest
import respx

from horatio_data_provider import DataProviderClient

BASE = "http://test"


@pytest.fixture
def client():
    return DataProviderClient(BASE)


@respx.mock
@pytest.mark.asyncio
async def test_raw_trades_url_and_body(client, parquet_bytes):
    route = respx.post(f"{BASE}/binance/raw_trades/read").mock(
        return_value=httpx.Response(200, content=parquet_bytes, headers={"content-type": "application/octet-stream"})
    )
    await client.binance.raw_trades("BTC").time_range("2025-01-01", "2025-01-02").fetch()
    assert route.called
    body = json.loads(route.calls[0].request.content)
    assert body["token"] == "BTC"
    assert body["since"] == "2025-01-01"
    assert body["until"] == "2025-01-02"


@respx.mock
@pytest.mark.asyncio
async def test_ohlcv_url_and_window(client, parquet_bytes):
    route = respx.post(f"{BASE}/binance/ohlcv/read").mock(
        return_value=httpx.Response(200, content=parquet_bytes, headers={"content-type": "application/octet-stream"})
    )
    await client.binance.ohlcv("BTC", "1h").time_range("2025-01-01", "2025-01-02").fetch()
    assert route.called
    body = json.loads(route.calls[0].request.content)
    assert body["token"] == "BTC"
    assert body["window"] == "1h"


@respx.mock
@pytest.mark.asyncio
async def test_raw_trades_cache(client, parquet_bytes):
    route = respx.post(f"{BASE}/binance/raw_trades/read").mock(
        return_value=httpx.Response(200, content=parquet_bytes, headers={"content-type": "application/octet-stream"})
    )
    await client.binance.raw_trades("BTC").time_range("2025-01-01", "2025-01-02").cache("force_replace").fetch()
    assert route.called
    body = json.loads(route.calls[0].request.content)
    assert body["cache"] is True
    assert body["cache_type"] == "force_replace"


@respx.mock
@pytest.mark.asyncio
async def test_flush_raw_trades(client):
    route = respx.post(f"{BASE}/binance/raw_trades/flush").mock(
        return_value=httpx.Response(200, content=b"{}", headers={"content-type": "application/json"})
    )
    await client.binance.flush_raw_trades(token="BTC")
    assert route.called
    body = json.loads(route.calls[0].request.content)
    assert body["token"] == "BTC"
