from unittest import TestCase
from unittest.mock import MagicMock, patch

from lib.options.options_hub_lib import build_options_hub_snapshot


class OptionsHubLibTests(TestCase):
    def test_build_options_hub_snapshot_disabled(self):
        out = build_options_hub_snapshot({"enabled": False})
        self.assertFalse(out["enabled"])
        self.assertTrue(out["ok"])

    @patch("lib.options.options_hub_lib._compute_options_stats", return_value={})
    @patch("lib.options.options_positions_lib.build_display_option_positions")
    def test_build_options_hub_snapshot_positions(self, mock_positions, _mock_stats):
        mock_positions.return_value = [
            {
                "inst_id": "ETH-USD_UM-260703-1800-C",
                "pos": 2,
                "upl": 9.9,
                "mark_px": 0.1,
                "close_preview": {"estimated_pnl": 1.5},
            }
        ]
        conn = MagicMock()
        conn.__enter__ = MagicMock(return_value=conn)
        conn.__exit__ = MagicMock(return_value=False)
        cfg = {
            "enabled": True,
            "exchange_options": object(),
            "options_api_ready": lambda ex: (True, ""),
            "fetch_option_positions": lambda ex: [
                {"instId": "ETH-USD_UM-260703-1800-C", "pos": "2", "upl": "1.5", "markPx": "0.1"}
            ],
            "fetch_options_balances": lambda ex: {"trading_usdc": 9.5, "funding_usdc": 12.0},
            "get_db": MagicMock(return_value=conn),
            "trade_budget": 10,
            "account_label": "OKX期权",
        }
        with patch("lib.options.options_target_lib.list_active_targets", return_value=[]):
            with patch("lib.options.options_target_lib.targets_by_inst", return_value={}):
                out = build_options_hub_snapshot(cfg)
        self.assertTrue(out["ok"], out.get("msg"))
        self.assertEqual(out["position_count"], 1)
        self.assertEqual(out["upl_total_usdc"], 1.5)
        self.assertEqual(out["trading_usdc"], 9.5)
        self.assertEqual(out.get("target_monitors"), [])
