import sys
import unittest
from pathlib import Path
from unittest.mock import patch


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

import refresh_top_pairs_backtest as refresh  # noqa: E402


class RefreshTopPairsTest(unittest.TestCase):
    def test_backtest_command_hardens_protocol(self):
        command = refresh.build_backtest_command(
            service="freqtrade",
            config_arg="user_data/config-auto.json",
            strategy="VolatilityBreakout",
            strategy_path="user_data/strategies/volatility_breakout",
            timerange="20260515-",
            timeframe="5m",
            fee=0.00035,
            result_dir_arg="user_data/backtest_results/auto-whitelist",
        )
        self.assertEqual(command[command.index("--timeframe") + 1], "5m")
        self.assertEqual(command[command.index("--fee") + 1], "0.00035")
        self.assertEqual(command[command.index("--cache") + 1], "none")

    @patch.object(refresh, "fetch_json")
    def test_forced_incumbent_keeps_real_volume_and_is_flagged(self, fetch_json):
        exchange_info = {
            "symbols": [
                {
                    "symbol": "BTCUSDT", "baseAsset": "BTC", "quoteAsset": "USDT",
                    "status": "TRADING", "contractType": "PERPETUAL",
                },
                {
                    "symbol": "EDGEUSDT", "baseAsset": "EDGE", "quoteAsset": "USDT",
                    "status": "TRADING", "contractType": "PERPETUAL",
                },
            ]
        }
        tickers = [
            {"symbol": "BTCUSDT", "quoteVolume": "12000000000"},
            {"symbol": "EDGEUSDT", "quoteVolume": "21000000"},
        ]
        fetch_json.side_effect = [exchange_info, tickers]

        rows = refresh.current_top_pairs(
            max_candidates=30,
            min_quote_volume=100_000_000,
            include={"EDGE"},
            exclude=set(),
        )

        self.assertEqual([row["pair"] for row in rows], ["BTC/USDT:USDT", "EDGE/USDT:USDT"])
        edge = rows[1]
        self.assertEqual(edge["quote_volume"], 21_000_000)
        self.assertTrue(edge["forced"])
        self.assertTrue(edge["below_min_quote_volume"])


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