import requests

TRALGO_URL = "https://tralgo.app/wp-admin/admin-ajax.php"

_HEADERS = {
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "X-Requested-With": "XMLHttpRequest",
    "Origin": "https://tralgo.app",
    "Referer": "https://tralgo.app/analytics-logbuch/",
}


def build_session(cookies):
    """Create a requests.Session with tralgo.app cookies set."""
    session = requests.Session()
    for name, value in cookies.items():
        session.cookies.set(name, value, domain="tralgo.app")
    return session


def send_trade(session, trade, api_key):
    """POST trade to Tralgo. Raises on HTTP error. Returns parsed JSON."""
    payload = {
        "action":               "insert_new_trade",
        "tradingaccount":       trade["account"],
        "instrument":           trade["instrument"],
        "type":                 trade["direction"],
        "lots":                 trade["lots"],
        "entry_price":          trade["entry_price"],
        "exit_price":           trade["exit_price"],
        "entry_datetime":       trade["entry_datetime"],
        "exit_datetime":        trade["exit_datetime"],
        "fees":                 0,
        "pnl":                  trade["pnl"],
        "net_pnl":              trade["pnl"],
        "pnl_ticks":            trade["pnl_ticks"],
        "tp_price": 0, "sl_price": 0,
        "tp_ticks": 0, "tp_usd":   0,
        "sl_ticks": 0, "sl_usd":   0,
        "setup":                "",
        "entry_specifications": "",
        "exit_specifications":  "",
        "mistakes":             "",
        "market_conditions":    "",
        "path":                 "",
        "trade_rating":         0,
        "review_status":        "Unreviewed",
        "journal":              "",
        "executions":           trade["executions"],
        "transfer_token":       api_key,
    }
    resp = session.post(TRALGO_URL, data=payload, headers=_HEADERS, timeout=15)
    resp.raise_for_status()
    try:
        return resp.json()
    except Exception:
        return resp.text
