# websocket_logger.py

import logging
import json
import base64
from typing import Any, Dict
from datetime import datetime

# Configure colored output for terminal
try:
    import colorama
    colorama.init()
    
    class Colors:
        HEADER = '\033[95m'
        BLUE = '\033[94m'
        GREEN = '\033[92m'
        WARNING = '\033[93m'
        FAIL = '\033[91m'
        ENDC = '\033[0m'
        BOLD = '\033[1m'
except ImportError:
    class Colors:
        HEADER = ''
        BLUE = ''
        GREEN = ''
        WARNING = ''
        FAIL = ''
        ENDC = ''
        BOLD = ''

def setup_websocket_logging():
    """Configure logging with custom formatter for WebSocket data"""
    
    class WebSocketFormatter(logging.Formatter):
        def format(self, record):
            timestamp = datetime.fromtimestamp(record.created).strftime('%H:%M:%S.%f')[:-3]
            
            if record.levelname == 'DEBUG':
                level_color = Colors.BLUE
            elif record.levelname == 'INFO':
                level_color = Colors.GREEN
            elif record.levelname == 'WARNING':
                level_color = Colors.WARNING
            else:
                level_color = Colors.FAIL
                
            return f"{Colors.HEADER}{timestamp}{Colors.ENDC} {level_color}{record.levelname:8}{Colors.ENDC} {record.getMessage()}"

    # Create console handler with custom formatter
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(WebSocketFormatter())
    
    # Configure websocket logger
    ws_logger = logging.getLogger('websocket')
    ws_logger.setLevel(logging.DEBUG)
    ws_logger.addHandler(console_handler)
    
    return ws_logger

logger = setup_websocket_logging()

def format_json(data: Any) -> str:
    """Format JSON data for readable output"""
    return json.dumps(data, indent=2)

def trace_websocket_message(msg: str, is_incoming: bool = True):
    """Trace WebSocket message with direction and content"""
    try:
        data = json.loads(msg)
        direction = "RECEIVED" if is_incoming else "SENDING"
        
        logger.debug(f"{Colors.BOLD}{direction} WEBSOCKET MESSAGE:{Colors.ENDC}")
        logger.debug(format_json(data))
        
    except json.JSONDecodeError:
        logger.warning(f"Invalid JSON in WebSocket message: {msg[:200]}...")

def trace_raydium_log(log_data: bytes):
    """Trace Raydium program log data"""
    try:
        # Extract key data points
        amount_in = int.from_bytes(log_data[0:8], 'little')
        amount_out = int.from_bytes(log_data[8:16], 'little')
        
        # Convert to SOL
        LAMPORTS_PER_SOL = 1_000_000_000
        amount_in_sol = amount_in / LAMPORTS_PER_SOL
        amount_out_sol = amount_out / LAMPORTS_PER_SOL
        
        logger.debug(f"{Colors.BOLD}RAYDIUM LOG DATA:{Colors.ENDC}")
        logger.debug(f"Amount In:  {amount_in_sol:.6f} SOL")
        logger.debug(f"Amount Out: {amount_out_sol:.6f} SOL")
        
        # Log hex dump for detailed debugging
        logger.debug(f"Raw Data Hex: {log_data.hex()[:100]}...")
        
    except Exception as e:
        logger.error(f"Error parsing Raydium log: {e}")

def trace_pool_update(pool_data: Dict):
    """Trace pool state updates"""
    try:
        logger.debug(f"{Colors.BOLD}POOL STATE UPDATE:{Colors.ENDC}")
        logger.debug(f"Pool Address: {pool_data.get('pubkey', 'Unknown')}")
        logger.debug(f"Base Reserve:  {pool_data.get('base_reserve', 0):.6f}")
        logger.debug(f"Quote Reserve: {pool_data.get('quote_reserve', 0):.6f}")
        
    except Exception as e:
        logger.error(f"Error tracing pool update: {e}")

# Modified monitor_mempool method
async def monitor_mempool(self):
    """Monitor mempool with enhanced debug tracing"""
    logger.info("Starting mempool monitoring...")
    
    while self.active:
        try:
            async with websockets.connect(
                self.config['rpc']['helius']['websocket'],
                ping_interval=30,
                ping_timeout=10
            ) as ws:
                # Log subscription request
                subscribe_msg = {
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "logsSubscribe",
                    "params": [
                        {"mentions": [self.config['programs']['raydium']]},
                        {"commitment": "processed"}
                    ]
                }
                trace_websocket_message(json.dumps(subscribe_msg), is_incoming=False)
                await ws.send(json.dumps(subscribe_msg))
                
                while self.active:
                    msg = await ws.recv()
                    trace_websocket_message(msg)
                    
                    data = json.loads(msg)
                    if 'params' in data and 'result' in data['params']:
                        logs = data['params']['result'].get('value', {}).get('logs', [])
                        
                        for log in logs:
                            if "ray_log:" in log:
                                logger.debug(f"{Colors.BOLD}PROCESSING RAYDIUM LOG{Colors.ENDC}")
                                raw_data = base64.b64decode(log.split('ray_log: ')[1].strip())
                                trace_raydium_log(raw_data)
                                
                                opportunity = await self.parser.parse_log(msg)
                                if opportunity:
                                    logger.debug(f"{Colors.GREEN}Opportunity detected!{Colors.ENDC}")
                                    logger.debug(format_json(opportunity.__dict__))
                    
        except websockets.exceptions.ConnectionClosed:
            logger.warning("WebSocket connection closed. Reconnecting...")
            await asyncio.sleep(1)
        except Exception as e:
            logger.error(f"Mempool monitoring error: {e}")
            await asyncio.sleep(1) can u add this kind of print logging to terminal instead of in a seperate file just i want without the color stuff just add the print logging for my websocket stuff please in the files im going to share and write the full entire script without changing my code just add the print logging so i can understand whats hjappening please