"""strategy_roll_ui_lib 单元测试."""
from __future__ import annotations

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

import lib.strategy.strategy_roll_ui_lib as roll_ui


def test_compute_roll_chain_metrics_short():
    group = {
        "id": 1,
        "direction": "short",
        "initial_take_profit": 60.0,
    }
    legs = [
        {"id": 10, "leg_index": 1, "amount": 3.0, "fill_price": 65.0, "status": "filled"},
        {"id": 11, "leg_index": 2, "amount": 5.0, "fill_price": 64.0, "status": "filled"},
    ]
    per_leg, group_metrics = roll_ui.compute_roll_chain_metrics(
        group,
        legs,
        qty_live=8.0,
        entry_live=63.5,
        monitor={"trigger_price": 66.0, "order_amount": 3.0},
    )
    assert per_leg[10]["avg_entry_after"] is not None
    assert per_leg[11]["avg_entry_after"] is not None
    assert group_metrics["reward_at_tp_usdt"] is not None
    assert group_metrics["initial_qty"] == 3.0
    assert group_metrics["current_qty"] == 8.0
    assert per_leg[11]["reward_at_tp_usdt"] >= per_leg[10]["reward_at_tp_usdt"]


def test_infer_initial_position_from_live():
    legs = [{"amount": 2.0, "fill_price": 64.0, "status": "filled"}]
    q0, e0 = roll_ui.infer_initial_position(5.0, 63.0, legs)
    assert q0 == 3.0
    assert abs(e0 - 62.3333333333) < 0.001


def test_reward_at_tp_long():
    # 毛利 20, 双边费 (200+220)*0.0005=0.21 → 净 19.79
    assert abs(roll_ui.reward_at_tp_usdt("long", 100.0, 110.0, 2.0) - 19.79) < 1e-6
