import copy
import json
import stat
import sys
import tempfile
import unittest
from pathlib import Path

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

import prepare_live_verification_config as mod  # noqa: E402


def source_config():
    return {
        "dry_run": True,
        "dry_run_wallet": 1000,
        "force_entry_enable": True,
        "timeframe": "5m",
        "max_open_trades": 4,
        "trading_mode": "futures",
        "margin_mode": "isolated",
        "entry_pricing": {"price_side": "same", "use_order_book": True},
        "unfilledtimeout": {"entry": 10},
        "order_types": {
            "stoploss": "market",
            "stoploss_on_exchange": True,
        },
        "exchange": {"key": "", "secret": "", "pair_whitelist": ["BTC/USDT:USDT"]},
        "unchanged": {"value": 7},
    }


class LiveConfigTest(unittest.TestCase):
    def test_only_frozen_behavior_fields_change(self):
        source = source_config()
        result = mod.build_live_config(source)
        expected = copy.deepcopy(source)
        expected["dry_run"] = False
        expected.pop("dry_run_wallet")
        expected["force_entry_enable"] = False
        self.assertEqual(result, expected)
        self.assertTrue(source["dry_run"])

    def test_rejects_inherited_exchange_credentials(self):
        source = source_config()
        source["exchange"]["key"] = "must-not-copy"
        with self.assertRaises(ValueError):
            mod.build_live_config(source)

    def test_private_atomic_output(self):
        with tempfile.TemporaryDirectory() as directory:
            path = Path(directory) / "config-live.json"
            mod.write_private_json(path, source_config())
            self.assertEqual(
                stat.S_IMODE(path.stat().st_mode),
                0o600,
            )
            self.assertTrue(json.loads(path.read_text())["dry_run"])


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