add absolute maximum debugging to this script here max max max debug logging import logging
import json
import os
import time
from solana_rust_bot import TradingCore, TradeParams

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('detailed_trading_test.log', encoding='utf-8')
    ]
)
logger = logging.getLogger(__name__)

class TradingSystemTest:
    def __init__(self, config_path: str):
        logger.info("=" * 50)
        logger.info("Initializing Trading System Test")
        logger.info("=" * 50)
        
        with open(config_path) as f:
            self.config = json.load(f)
            logger.debug(f"Full configuration:\n{json.dumps(self.config, indent=2)}")
        
        trading_config = {
            "compute_limit": self.config['execution']['compute_limit'],
            "priority_fee": 2000000,  # Optimized priority fee
            "max_priority_fee": self.config['execution']['max_priority_fee'],
            "min_priority_fee": self.config['execution']['min_priority_fee'],
            "fee_multiplier": self.config['execution']['fee_multiplier'],
            "slippage": self.config['execution']['slippage'],
            "retry_count": 3,  # Increased retries
            "position_size": self.config['trading']['position']['size'],
            "max_position_size": self.config['trading']['position']['max_size'],
            "gas_reserve": self.config['trading']['position']['gas_reserve']
        }

        logger.info("Initializing with trading configuration:")
        logger.info(json.dumps(trading_config, indent=2))
        
        private_key = os.getenv('SOLANA_PRIVATE_KEY')
        if not private_key:
            raise ValueError("SOLANA_PRIVATE_KEY environment variable not set")
        
        if not all(c in '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' for c in private_key):
            raise ValueError("Invalid base58 private key format")
            
        logger.debug(f"Using RPC endpoint: {self.config['rpc']['helius']['endpoint']}")
        
        self.trader = TradingCore(
            secret_key=private_key,
            rpc_url=self.config['rpc']['helius']['endpoint'],
            config_json=json.dumps(trading_config)
        )

    def test_rpc_connection(self):
        """Test RPC connection and wallet balance"""
        logger.info("\n=== Testing RPC Connection ===")
        try:
            balance = self.trader.get_balance()
            logger.info(f"Wallet balance: {balance} SOL")
            
            min_required = self.config['trading']['position']['gas_reserve']
            if balance < min_required:
                logger.warning(f"Low balance: {balance} SOL (minimum required: {min_required} SOL)")
                return False
            
            wsol_balance = self.trader.get_wsol_balance()
            logger.info(f"WSOL balance: {wsol_balance}")
                
            return True
        except Exception as e:
            logger.error(f"RPC connection failed: {e}", exc_info=True)
            return False

    def test_pool_config(self):
        """Test pool configuration and data loading"""
        logger.info("\n=== Testing Pool Configuration ===")
        try:
            pool_data = {
                'amm_id': self.config['accounts']['sol_wsol']['amm_id'],
                'base_mint': self.config['accounts']['sol_wsol']['base_mint'],
                'quote_mint': self.config['accounts']['sol_wsol']['quote_mint'],
                'amm_authority': self.config['accounts']['sol_wsol']['amm_authority'],
                'amm_open_orders': self.config['accounts']['sol_wsol']['amm_open_orders'],
                'amm_target': self.config['accounts']['sol_wsol']['amm_target'],
                'pool_coin_token_account': self.config['accounts']['sol_wsol']['pool_coin_token_account'],
                'pool_pc_token_account': self.config['accounts']['sol_wsol']['pool_pc_token_account'],
                'serum_market': self.config['accounts']['sol_wsol']['serum_market'],
                'serum_bids': self.config['accounts']['sol_wsol']['serum_bids'],
                'serum_asks': self.config['accounts']['sol_wsol']['serum_asks'],
                'serum_events': self.config['accounts']['sol_wsol']['serum_events'],
                'vault_signer': self.config['accounts']['sol_wsol']['vault_signer'],
                'token_mint': self.config['accounts']['sol_wsol']['base_mint'],
                'wsol_token_account': self.config['accounts']['sol_wsol']['wsol_token_account']
            }
            
            logger.debug("Pool Configuration Details:")
            for key, value in pool_data.items():
                logger.debug(f"{key}: {value}")
            
            self.trader.update_pool(pool_data)
            logger.info("Pool configuration successful")
            return True
            
        except Exception as e:
            logger.error(f"Pool configuration failed: {e}", exc_info=True)
            return False

    def test_trade_params(self):
        """Test trade parameter validation"""
        logger.info("\n=== Testing Trade Parameters ===")
        try:
            amount_in = 0.005  # Fixed test amount
            slippage = self.config['execution']['slippage']
            min_amount_out = amount_in * (1 - slippage)
            
            param_dict = {
                "pool_address": self.config['accounts']['sol_wsol']['amm_id'],
                "amount_in": amount_in,
                "min_amount_out": min_amount_out,
                "priority_fee": 2000000
            }
            
            logger.debug("Trade Parameter Details:")
            logger.debug(f"Amount In: {amount_in} SOL ({amount_in * 1e9} lamports)")
            logger.debug(f"Min Amount Out: {min_amount_out} SOL ({min_amount_out * 1e9} lamports)")
            logger.debug(f"Slippage: {slippage * 100}%")
            logger.debug(f"Pool Address: {param_dict['pool_address']}")
            logger.debug(f"Priority Fee: {param_dict['priority_fee']}")
            
            params = TradeParams(
                pool_address=param_dict["pool_address"],
                amount_in=param_dict["amount_in"],
                min_amount_out=param_dict["min_amount_out"]
            )
            
            logger.info("Trade parameters validated successfully")
            return params
            
        except Exception as e:
            logger.error(f"Trade parameter validation failed: {e}", exc_info=True)
            return None

    def test_dry_run(self):
        """Execute a dry run trade"""
        logger.info("\n=== Executing Dry Run Trade ===")
        try:
            initial_sol = self.trader.get_balance()
            initial_wsol = self.trader.get_wsol_balance()
            logger.info(f"Initial SOL balance: {initial_sol}")
            logger.info(f"Initial WSOL balance: {initial_wsol}")
            
            transfer_amount = 0.005  # Fixed test amount
            fee_buffer = (2000000 / 1e9) * 3  # Buffer for priority fee
            total_required = transfer_amount + fee_buffer
            
            if initial_sol < total_required:
                logger.error(f"Insufficient balance for transfer + fees. Need {total_required} SOL")
                return False
            
            logger.info("Testing SOL to WSOL transfer...")
            logger.info(f"Attempting transfer with 2000000 lamport priority fee...")
            
            max_retries = 3
            for attempt in range(max_retries):
                try:
                    transfer_result = self.trader.transfer_to_wsol(transfer_amount)
                    if transfer_result:
                        break
                except Exception as e:
                    if attempt < max_retries - 1:
                        time.sleep(2 ** attempt)  # Exponential backoff
                        continue
                    raise e
            
            if not transfer_result:
                logger.error("Transfer failed after retries")
                return False
                
            logger.info(f"Transfer successful: {transfer_result}")
            time.sleep(3)  # Allow state updates
            
            post_transfer_wsol = self.trader.get_wsol_balance()
            logger.info(f"Post-transfer WSOL balance: {post_transfer_wsol}")
            
            if post_transfer_wsol < transfer_amount * 0.98:  # 2% tolerance
                logger.error(f"Transfer verification failed. Expected ~{transfer_amount}, got {post_transfer_wsol}")
                return False
            
            logger.info("Transfer verified successfully")
            return True
            
        except Exception as e:
            logger.error(f"Dry run failed: {e}", exc_info=True)
            return False

    def run_all_tests(self):
        """Run all system tests"""
        tests = {
            "RPC Connection": self.test_rpc_connection,
            "Pool Configuration": self.test_pool_config,
            "Trade Parameters": self.test_trade_params,
            "Dry Run Trade": self.test_dry_run
        }

        results = {}
        all_passed = True
        
        logger.info("\n=== Starting Trading System Tests ===\n")
        
        for name, test in tests.items():
            logger.info(f"\n=== Running {name} Test ===")
            try:
                result = test()
                status = "PASSED" if result else "FAILED"
                if not result:
                    all_passed = False
                logger.info(f"Test {name}: {status}")
            except Exception as e:
                logger.error(f"Test {name} failed with error: {e}", exc_info=True)
                status = "ERROR"
                all_passed = False
            
            results[name] = status
            print(f"{name}: {status}")

        logger.info("\n=== Test Summary ===")
        for test, status in results.items():
            logger.info(f"{test}: {status}")
        
        logger.info(f"\nOverall Status: {'ALL TESTS PASSED' if all_passed else 'SOME TESTS FAILED'}")
        return results, all_passed

def main():
    try:
        logger.info("Starting detailed trading system test...")
        tester = TradingSystemTest('config.json')
        results, passed = tester.run_all_tests()
        
        if not passed:
            logger.error("Some tests failed - check detailed_trading_test.log for more information")
        
        exit(0 if passed else 1)
    except Exception as e:
        logger.error(f"Fatal error in test execution: {e}", exc_info=True)
        exit(1)

if __name__ == "__main__":
    main()