import requests

TRALGO_URL = "https://tralgo.app/wp-json/trade-api/v1/add-trade"

_DIRECTION = {"Long": "B", "Short": "S", "B": "B", "S": "S"}


def _trade_payload(trade):
    return {
        "tradingaccount": trade["account"],
        "instrument":     trade["instrument"],
        "type":           _DIRECTION.get(trade["direction"], trade["direction"]),
        "lots":           abs(trade["lots"]),
        "entry_price":    trade["entry_price"],
        "exit_price":     trade["exit_price"],
        "entry_datetime": trade["entry_datetime"],
        "exit_datetime":  trade["exit_datetime"],
        "fees":           0,
        "transfer_token": trade["trade_id"],
    }


def send_trade(api_key, trade):
    """POST a single trade. Raises on HTTP error."""
    return send_trades_bulk(api_key, [trade])


def send_trades_bulk(api_key, trades):
    """POST one or more trades in a single request. Raises on HTTP error."""
    if not trades:
        return
    headers = {"API-Key": api_key, "Content-Type": "application/json"}
    if len(trades) == 1:
        body = _trade_payload(trades[0])
    else:
        body = {"trades": [_trade_payload(t) for t in trades]}
    resp = requests.post(TRALGO_URL, json=body, headers=headers, timeout=15)
    resp.raise_for_status()
    try:
        return resp.json()
    except Exception:
        return resp.text
