"""期权净盈亏汇总与持仓卡口径一致."""
from unittest import TestCase
from unittest.mock import patch

from lib.options.options_positions_lib import (
    display_pnl_from_option_row,
    net_pnl_from_display_row,
    sum_options_net_pnl_usdc,
)


class OptionsNetPnlSumTests(TestCase):
    def test_net_pnl_from_display_row(self):
        self.assertEqual(
            net_pnl_from_display_row({"close_preview": {"estimated_pnl": -2.8}, "premium_paid": 4.95}),
            -2.8,
        )
        self.assertIsNone(
            net_pnl_from_display_row({"close_preview": {"bid_invalid": True, "estimated_pnl": -1}})
        )
        self.assertEqual(
            net_pnl_from_display_row(
                {
                    "close_preview": {"total_received": 2.15, "covered_sheets": 1},
                    "premium_paid": 4.95,
                }
            ),
            round(2.15 - 4.95, 4),
        )
        # bid 无效时 total_received=0 不得算出 −权利金
        self.assertIsNone(
            net_pnl_from_display_row(
                {
                    "close_preview": {
                        "bid_invalid": True,
                        "total_received": 0.0,
                        "covered_sheets": 0,
                    },
                    "premium_paid": 9.49,
                    "upl": -4.2,
                }
            )
        )

    def test_display_pnl_falls_back_to_exchange_upl(self):
        self.assertEqual(
            display_pnl_from_option_row(
                {
                    "close_preview": {"bid_invalid": True, "total_received": 0.0},
                    "premium_paid": 9.49,
                    "upl": -4.2,
                }
            ),
            -4.2,
        )

    @patch("lib.options.options_positions_lib.build_display_option_positions")
    def test_sum_options_net_pnl_usdc(self, mock_build):
        mock_build.return_value = [
            {"close_preview": {"estimated_pnl": -2.8}},
            {"close_preview": {"estimated_pnl": 1.0}},
            {"close_preview": {"bid_invalid": True, "estimated_pnl": 9}, "upl": -0.5},
        ]
        cfg = {"fetch_option_positions": lambda ex: [{"instId": "X"}]}
        self.assertEqual(sum_options_net_pnl_usdc(cfg, object()), -2.3)


if __name__ == "__main__":
    from unittest import main

    main()
