from __future__ import annotations

import pytest
from fastapi.testclient import TestClient

# نضبط متغيرات البيئة قبل استيراد التطبيق
import os
os.environ.setdefault("SIGNAL_TOKEN", "test-secret-token")
os.environ.setdefault("TRADING_MODE", "SIMULATION")
os.environ.setdefault("SYMBOLS", "BTCUSDT,ETHUSDT")


from main import app  # noqa: E402

client = TestClient(app)

VALID_SIGNAL = {
    "token": "test-secret-token",
    "symbol": "BTCUSDT",
    "action": "BUY",
    "quantity": 0.001,
}


def test_valid_signal_returns_202():
    resp = client.post("/signal", json=VALID_SIGNAL)
    assert resp.status_code == 202
    data = resp.json()
    assert data["status"] == "queued"
    assert data["symbol"] == "BTCUSDT"


def test_wrong_token_returns_401():
    payload = {**VALID_SIGNAL, "token": "wrong-token"}
    resp = client.post("/signal", json=payload)
    assert resp.status_code == 401


def test_unknown_symbol_returns_400():
    payload = {**VALID_SIGNAL, "symbol": "XYZUSDT"}
    resp = client.post("/signal", json=payload)
    assert resp.status_code == 400


def test_negative_quantity_returns_422():
    payload = {**VALID_SIGNAL, "quantity": -1.0}
    resp = client.post("/signal", json=payload)
    assert resp.status_code == 422


def test_zero_quantity_returns_422():
    payload = {**VALID_SIGNAL, "quantity": 0.0}
    resp = client.post("/signal", json=payload)
    assert resp.status_code == 422


def test_health_endpoint():
    resp = client.get("/health")
    assert resp.status_code == 200
    data = resp.json()
    assert data["status"] == "ok"
    assert data["mode"] == "SIMULATION"
