#!/usr/bin/env python3
"""
Test script to verify that the bot configuration and format string fixes work correctly.
"""

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

from config import Config

def test_config_fixes():
    """Test that the configuration changes work correctly."""
    print("šŸ”§ Configuration Fixes Test")
    print("=" * 50)
    
    # Test that the new configuration variables exist
    try:
        token = Config.DEFAULT_TRADING_TOKEN
        risk_enabled = Config.RISK_MANAGEMENT_ENABLED
        stop_loss = Config.STOP_LOSS_PERCENTAGE
        heartbeat = Config.BOT_HEARTBEAT_SECONDS
        
        print(f"āœ… DEFAULT_TRADING_TOKEN: {token}")
        print(f"āœ… RISK_MANAGEMENT_ENABLED: {risk_enabled}")
        print(f"āœ… STOP_LOSS_PERCENTAGE: {stop_loss}%")
        print(f"āœ… BOT_HEARTBEAT_SECONDS: {heartbeat}")
        
        # Test that old variables are gone
        try:
            amount = Config.DEFAULT_TRADE_AMOUNT
            print(f"āŒ DEFAULT_TRADE_AMOUNT still exists: {amount}")
        except AttributeError:
            print("āœ… DEFAULT_TRADE_AMOUNT properly removed")
        
        try:
            symbol = Config.DEFAULT_TRADING_SYMBOL
            print(f"āŒ DEFAULT_TRADING_SYMBOL still exists: {symbol}")
        except AttributeError:
            print("āœ… DEFAULT_TRADING_SYMBOL properly removed")
            
    except AttributeError as e:
        print(f"āŒ Configuration error: {e}")
        return False
    
    return True

def test_format_strings():
    """Test that format strings work correctly."""
    print("\nšŸ“ Format String Test")
    print("=" * 50)
    
    try:
        # Test the format parameters that would be used in telegram bot
        symbol = Config.DEFAULT_TRADING_TOKEN
        network = "Testnet" if Config.HYPERLIQUID_TESTNET else "Mainnet"
        risk_enabled = Config.RISK_MANAGEMENT_ENABLED
        stop_loss = Config.STOP_LOSS_PERCENTAGE
        heartbeat = Config.BOT_HEARTBEAT_SECONDS
        
        # Test format string similar to what's used in the bot
        test_format = """
āš™ļø Configuration:
• Default Token: {symbol}
• Network: {network}
• Risk Management: {risk_enabled}
• Stop Loss: {stop_loss}%
• Monitoring: Every {heartbeat} seconds
        """.format(
            symbol=symbol,
            network=network,
            risk_enabled=risk_enabled,
            stop_loss=stop_loss,
            heartbeat=heartbeat
        )
        
        print("āœ… Format string test successful:")
        print(test_format.strip())
        
    except KeyError as e:
        print(f"āŒ Format string error: {e}")
        return False
    except Exception as e:
        print(f"āŒ Unexpected error: {e}")
        return False
    
    return True

def test_timestamp_handling():
    """Test timestamp handling for external trades."""
    print("\nā° Timestamp Handling Test")
    print("=" * 50)
    
    from datetime import datetime, timedelta
    
    try:
        # Test different timestamp formats
        test_timestamps = [
            1733155660,  # Unix timestamp (seconds)
            1733155660000,  # Unix timestamp (milliseconds)
            "2024-12-02T15:47:40",  # ISO format
            "2024-12-02T15:47:40.123Z",  # ISO with Z
        ]
        
        base_time = (datetime.now() - timedelta(hours=1)).isoformat()
        
        for ts in test_timestamps:
            try:
                # Test the conversion logic from the bot
                if isinstance(ts, (int, float)):
                    # Assume it's a unix timestamp
                    ts_str = datetime.fromtimestamp(ts / 1000 if ts > 1e10 else ts).isoformat()
                else:
                    ts_str = str(ts)
                
                # Test comparison
                comparison_result = ts_str > base_time
                print(f"āœ… Timestamp {ts} -> {ts_str} (comparison: {comparison_result})")
                
            except Exception as e:
                print(f"āŒ Error processing timestamp {ts}: {e}")
                return False
                
        print("āœ… All timestamp formats handled correctly")
        
    except Exception as e:
        print(f"āŒ Timestamp handling error: {e}")
        return False
    
    return True

if __name__ == "__main__":
    print("šŸš€ Bot Fixes Verification Test")
    print("=" * 60)
    
    # Run all tests
    tests = [
        test_config_fixes,
        test_format_strings,
        test_timestamp_handling
    ]
    
    results = []
    for test in tests:
        try:
            result = test()
            results.append(result)
        except Exception as e:
            print(f"āŒ Test failed with exception: {e}")
            results.append(False)
    
    print("\n" + "=" * 60)
    
    if all(results):
        print("šŸŽ‰ All tests passed! Bot fixes are working correctly.")
        print("āœ… Configuration cleanup successful")
        print("āœ… Format string errors fixed")
        print("āœ… Timestamp comparison issues resolved")
    else:
        print("āš ļø Some tests failed. Please check the issues above.")
        failed_count = len([r for r in results if not r])
        print(f"āŒ {failed_count}/{len(results)} tests failed")