#!/usr/bin/env python3
"""
Event Watcher
Monitors specific contract events
"""

import logging
from typing import Dict, List, Optional
from web3 import Web3
from web3.contract import Contract

logger = logging.getLogger(__name__)

class EventWatcher:
    """Watches for specific contract events"""
    
    def __init__(
        self,
        w3: Web3,
        contract_address: str,
        event_name: str,
        alert_manager=None
    ):
        self.w3 = w3
        self.contract_address = contract_address
        self.event_name = event_name
        self.alert_manager = alert_manager
        self.last_block = w3.eth.block_number
        self.contract = self._load_contract()
        
    def _load_contract(self) -> Optional[Contract]:
        """Load contract ABI and create contract instance"""
        # In production, load ABI from file or contract verification
        # For now, use minimal ABI for event watching
        try:
            # Get contract code to verify it exists
            code = self.w3.eth.get_code(self.contract_address)
            if code == b'':
                logger.warning(f"Contract {self.contract_address} has no code")
                return None
            
            # Minimal ABI for event watching
            # In production, load full ABI
            abi = []  # Placeholder - load actual ABI
            return self.w3.eth.contract(address=self.contract_address, abi=abi)
        except Exception as e:
            logger.error(f"Failed to load contract: {e}")
            return None
    
    def process_events(self):
        """Process new events since last check"""
        try:
            current_block = self.w3.eth.block_number
            from_block = max(self.last_block + 1, current_block - 1000)  # Look back max 1000 blocks
            
            if from_block > current_block:
                return
            
            # Get events (using eth_getLogs)
            # In production, use contract event filters
            events = self._get_events(from_block, current_block)
            
            for event in events:
                self._handle_event(event)
            
            self.last_block = current_block
            
        except Exception as e:
            logger.error(f"Error processing events: {e}", exc_info=True)
    
    def _get_events(self, from_block: int, to_block: int) -> List[Dict]:
        """Get events from contract"""
        # Placeholder - implement actual event fetching
        # This would use contract event filters or eth_getLogs
        return []
    
    def _handle_event(self, event: Dict):
        """Handle a single event"""
        logger.info(f"Event {self.event_name} detected: {event}")
        
        # Update metrics based on event type
        if self.event_name == 'Deposit':
            # Handle deposit event
            pass
        elif self.event_name == 'ClaimSubmitted':
            # Handle claim submitted event
            pass
        elif self.event_name == 'ClaimChallenged':
            # Handle challenge event
            pass
        
        # Send alert if needed
        if self.alert_manager:
            self.alert_manager.check_event(event, self.event_name)

