"""Gate 持仓指标:全仓保证金不得误用 unrealised_pnl."""
from __future__ import annotations

import unittest


class TestGatePositionMetrics(unittest.TestCase):
    def test_cross_margin_not_equal_unrealised_pnl(self):
        from crypto_monitor_gate.app import parse_ccxt_position_metrics

        pos = {
            "side": "long",
            "contracts": 400,
            "collateral": 21.19,
            "initialMargin": None,
            "notional": 3098.54,
            "unrealizedPnl": 21.19,
            "markPrice": 77463.5,
            "leverage": 0,
            "marginMode": "cross",
            "symbol": "BTC/USDT:USDT",
            "info": {
                "value": "3098.54",
                "leverage": "0",
                "cross_leverage_limit": "20",
                "margin": "21.19",
                "unrealised_pnl": "21.19",
                "mark_price": "77463.5",
            },
        }
        out = parse_ccxt_position_metrics(pos, order_leverage=20)
        self.assertIsNotNone(out)
        self.assertAlmostEqual(out["unrealized_pnl"], 21.19)
        self.assertGreater(out["initial_margin"], 150)
        self.assertLess(out["initial_margin"], 160)
        pct = out["unrealized_pnl"] / out["initial_margin"] * 100
        self.assertGreater(pct, 12)
        self.assertLess(pct, 16)

    def test_cross_margin_trusts_api_when_sane(self):
        from crypto_monitor_gate.app import parse_ccxt_position_metrics

        pos = {
            "side": "long",
            "contracts": 1,
            "collateral": 157.03,
            "notional": 3098.54,
            "unrealizedPnl": 21.19,
            "leverage": 0,
            "marginMode": "cross",
            "info": {
                "value": "3098.54",
                "leverage": "0",
                "cross_leverage_limit": "20",
                "margin": "157.03",
                "unrealised_pnl": "21.19",
            },
        }
        out = parse_ccxt_position_metrics(pos, order_leverage=20)
        self.assertIsNotNone(out)
        self.assertAlmostEqual(out["initial_margin"], 157.03)

    def test_isolated_uses_api_margin(self):
        from crypto_monitor_gate.app import parse_ccxt_position_metrics

        pos = {
            "side": "long",
            "contracts": 10,
            "collateral": 88.5,
            "notional": 885.0,
            "unrealizedPnl": 3.2,
            "leverage": 10,
            "marginMode": "isolated",
            "info": {"value": "885", "leverage": "10", "margin": "88.5", "unrealised_pnl": "3.2"},
        }
        out = parse_ccxt_position_metrics(pos, order_leverage=10)
        self.assertIsNotNone(out)
        self.assertAlmostEqual(out["initial_margin"], 88.5)


if __name__ == "__main__":
    unittest.main()
