import importlib.util
import os
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def test_autotrader_script_is_blocked_by_default():
    env = os.environ.copy()
    env.pop("CTB_ALLOW_LEGACY_AUTOTRADER", None)
    result = subprocess.run(
        [sys.executable, str(ROOT / "AutoTrader.py")],
        cwd=ROOT,
        env=env,
        text=True,
        capture_output=True,
        timeout=20,
    )

    assert result.returncode == 2
    assert "Legacy AutoTrader disabled; use src/tools/preflight.py and v76 executors" in result.stdout


def test_backup_autotrader_does_not_initialize_exchange_on_import_without_guard():
    env = os.environ.copy()
    env.pop("CTB_ALLOW_LEGACY_AUTOTRADER", None)
    result = subprocess.run(
        [sys.executable, str(ROOT / "AutoTrader_backup_2026-03-29_17-30.py")],
        cwd=ROOT,
        env=env,
        text=True,
        capture_output=True,
        timeout=20,
    )

    assert result.returncode == 2
    assert "Legacy AutoTrader disabled" in result.stdout


def test_panic_close_still_requires_exact_confirmation(monkeypatch, capsys):
    monkeypatch.setenv("HL_API_PRIVATE_KEY", "dummy")
    monkeypatch.setenv("HL_WALLET_ADDRESS", "0x1234567890abcdef")
    spec = importlib.util.spec_from_file_location("panic_close", ROOT / "panic_close.py")
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)

    code = module.main([])

    out = capsys.readouterr().out
    assert code == 3
    assert "PANIC CLOSE blockiert" in out
