"""永续固定费率净盈亏."""
from __future__ import annotations

import os
import sys
import unittest
from pathlib import Path

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

from lib.trade.trade_fee_lib import (  # noqa: E402
    estimate_roundtrip_fee_usdt,
    net_pnl_after_fee,
    notional_usdt,
    taker_fee_rate,
)


class TestTradeFeeLib(unittest.TestCase):
    def test_default_rate(self):
        os.environ.pop("PERP_TAKER_FEE_RATE", None)
        self.assertAlmostEqual(taker_fee_rate(), 0.0005)

    def test_notional(self):
        self.assertAlmostEqual(notional_usdt(100, 2, 1.0), 200.0)
        self.assertAlmostEqual(notional_usdt(62000, 78, 0.0001), 483.6, places=2)

    def test_roundtrip_fee_qty(self):
        # 开 100*2=200, 平 110*2=220, 费=(200+220)*0.0005=0.21
        fee = estimate_roundtrip_fee_usdt(100, 110, 2.0, 1.0, rate=0.0005)
        self.assertAlmostEqual(fee, 0.21, places=6)

    def test_net_long_matches_checklist(self):
        # 毛利 20, 费 0.21 → 净 19.79
        net = net_pnl_after_fee(20.0, 100, 110, 2.0, 1.0, rate=0.0005)
        self.assertAlmostEqual(net, 19.79, places=4)

    def test_open_notional_fallback(self):
        # 无张数:开名义 1000, 出场 110/100 → 平 1100, 费=1.05
        fee = estimate_roundtrip_fee_usdt(100, 110, open_notional=1000, rate=0.0005)
        self.assertAlmostEqual(fee, 1.05, places=6)
        net = net_pnl_after_fee(50.0, 100, 110, open_notional=1000, rate=0.0005)
        self.assertAlmostEqual(net, 48.95, places=4)


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