from __future__ import annotations

import pytest

from src.market_data.acquisition.adapters.dzengi.models import (
    DzengiTicker24hrResponse,
)
from src.market_data.acquisition.adapters.dzengi.parser import parse_quote
from src.market_data.acquisition.exceptions import QuoteParseError
from src.market_data.acquisition.validation.schema import validate_quote_schema


def _document() -> dict[str, object]:
    return {
        "symbol": "BTC/USD_LEVERAGE",
        "lastPrice": "64159.45",
        "bidPrice": "64159.45",
        "askPrice": "64159.55",
        "closeTime": 1783887270312,
        "highPrice": "64261.45",
        "volume": "9.6002",
    }


def test_parse_quote_builds_dzengi_transport_model() -> None:
    validated = validate_quote_schema(_document())

    result = parse_quote(validated)

    assert result == DzengiTicker24hrResponse(
        symbol="BTC/USD_LEVERAGE",
        last_price="64159.45",
        bid_price="64159.45",
        ask_price="64159.55",
        close_time=1783887270312,
    )


def test_parse_quote_ignores_unrelated_24hr_statistics() -> None:
    document = _document()
    document["openPrice"] = "63785.75"
    document["weightedAvgPrice"] = "64159.50"

    result = parse_quote(validate_quote_schema(document))

    assert result.symbol == "BTC/USD_LEVERAGE"
    assert not hasattr(result, "open_price")
    assert not hasattr(result, "weighted_avg_price")


def test_parse_quote_accepts_json_numbers_for_prices() -> None:
    document = _document()
    document["lastPrice"] = 64159.45
    document["bidPrice"] = 64159
    document["askPrice"] = 64160

    result = parse_quote(validate_quote_schema(document))

    assert result.last_price == 64159.45
    assert result.bid_price == 64159
    assert result.ask_price == 64160


def test_parse_quote_rejects_boolean_price() -> None:
    document = _document()
    document["lastPrice"] = True

    with pytest.raises(QuoteParseError, match="lastPrice"):
        parse_quote(validate_quote_schema(document))


def test_parse_quote_rejects_non_integer_close_time() -> None:
    document = _document()
    document["closeTime"] = "1783887270312"

    with pytest.raises(QuoteParseError, match="closeTime"):
        parse_quote(validate_quote_schema(document))
