"""中控条件单列表:子代理与 Flask exchange_tpsl 合并去重."""

from manual_trading_hub.hub import _merge_conditional_orders_no_dup, _merge_flask_exchange_tpsl


def test_merge_skips_duplicate_trigger_prices():
    existing = [
        {
            "id": "100",
            "label": "市价 买入 ·只减仓",
            "trigger_price": 57,
            "amount": 11,
        },
        {
            "id": "101",
            "label": "市价 买入 ·只减仓",
            "trigger_price": 71,
            "amount": 11,
        },
    ]
    extra = [
        {"id": "", "label": "止损 57", "trigger_price": 57, "amount": 11},
        {"id": "", "label": "止盈 71", "trigger_price": 71, "amount": 11},
    ]
    merged = _merge_conditional_orders_no_dup(existing, extra)
    assert len(merged) == 2
    assert {round(o["trigger_price"]) for o in merged} == {57, 71}


def test_merge_uses_extra_when_existing_empty():
    extra = [{"id": "1", "label": "止损 57", "trigger_price": 57}]
    assert _merge_conditional_orders_no_dup([], extra) == extra


def test_merge_flask_skips_duplicate_sl_when_agent_has_both():
    agent_row = {
        "agent": {
            "positions": [
                {
                    "symbol": "SOL/USDT:USDT",
                    "side": "short",
                    "conditional_orders": [
                        {"label": "止盈 76", "trigger_price": 76, "algo_id": "1"},
                        {"label": "止损 84.1", "trigger_price": 84.1, "algo_id": "1"},
                        {"label": "止损", "trigger_price": 84.1},
                    ],
                }
            ]
        }
    }
    snap = {
        "order_prices": [
            {
                "symbol": "SOL/USDT:USDT",
                "side": "short",
                "exchange_tpsl": {
                    "sl": {"trigger_price": 84.1, "order_id": "old"},
                    "tp": {"trigger_price": 76, "order_id": "old"},
                },
            }
        ]
    }
    _merge_flask_exchange_tpsl(agent_row, snap, None)
    cond = agent_row["agent"]["positions"][0]["conditional_orders"]
    sl_rows = [o for o in cond if "止损" in (o.get("label") or "")]
    assert len(sl_rows) == 1
    assert len(cond) == 2
