from __future__ import annotations

import os
from datetime import datetime, timedelta, timezone
from unittest.mock import patch

import pytest

os.environ.setdefault("SIGNAL_TOKEN", "test-secret-token")
os.environ.setdefault("TRADING_MODE", "SIMULATION")
os.environ.setdefault("SYMBOLS", "BTCUSDT,ETHUSDT")


from execution.executor import TradeExecutor
from price.cache import price_cache


@pytest.mark.asyncio
async def test_simulation_buy_logs_correct_notional(caplog):
    import logging
    price_cache.set("BTCUSDT", 65000.0)

    ex = TradeExecutor()
    with caplog.at_level(logging.INFO):
        result = await ex.execute({
            "symbol": "BTCUSDT",
            "action": "BUY",
            "quantity": 0.01,
        })

    assert result["status"] == "simulated"
    assert result["price"] == 65000.0
    assert "notional=650.00" in caplog.text


@pytest.mark.asyncio
async def test_simulation_sell():
    price_cache.set("ETHUSDT", 3200.0)
    ex = TradeExecutor()
    result = await ex.execute({
        "symbol": "ETHUSDT",
        "action": "SELL",
        "quantity": 0.5,
    })
    assert result["status"] == "simulated"
    assert result["action"] == "SELL"


@pytest.mark.asyncio
async def test_stale_cache_returns_failed():
    price_cache.set("BTCUSDT", 65000.0)
    # تزوير الطابع الزمني
    old_time = datetime.now(timezone.utc) - timedelta(seconds=30)
    with price_cache._lock:
        price_cache._last_updated["BTCUSDT"] = old_time

    ex = TradeExecutor()
    result = await ex.execute({
        "symbol": "BTCUSDT",
        "action": "BUY",
        "quantity": 0.01,
    })
    assert result["status"] == "failed"
    assert "قديم" in result["reason"]


@pytest.mark.asyncio
async def test_unknown_symbol_not_in_cache_returns_failed():
    ex = TradeExecutor()
    result = await ex.execute({
        "symbol": "BNBUSDT",
        "action": "BUY",
        "quantity": 1.0,
    })
    assert result["status"] == "failed"
