#!/usr/bin/env python3
"""
Metrics Exporter
Exports bridge metrics to Prometheus
"""

import time
import logging
from typing import Dict
from prometheus_client import start_http_server, Gauge, Counter, Histogram

logger = logging.getLogger(__name__)

class MetricsExporter:
    """Exports bridge metrics to Prometheus"""
    
    def __init__(self, port: int = 8000):
        self.port = port
        
        # Define metrics
        self.deposits_total = Counter(
            'bridge_deposits_total',
            'Total number of deposits',
            ['chain', 'asset']
        )
        
        self.claims_total = Counter(
            'bridge_claims_total',
            'Total number of claims',
            ['status']  # submitted, challenged, finalized
        )
        
        self.challenges_total = Counter(
            'bridge_challenges_total',
            'Total number of challenges',
            ['result']  # successful, failed
        )
        
        self.bonds_posted = Gauge(
            'bridge_bonds_posted_wei',
            'Total bonds posted',
            ['relayer']
        )
        
        self.bonds_slashed = Counter(
            'bridge_bonds_slashed_wei',
            'Total bonds slashed',
            ['relayer']
        )
        
        self.liquidity_total = Gauge(
            'bridge_liquidity_total_wei',
            'Total liquidity in pool',
            ['asset_type']  # ETH, WETH
        )
        
        self.liquidity_pending = Gauge(
            'bridge_liquidity_pending_claims_wei',
            'Pending claims amount',
            ['asset_type']
        )
        
        self.liquidity_available = Gauge(
            'bridge_liquidity_available_wei',
            'Available liquidity',
            ['asset_type']
        )
        
        self.liquidity_ratio = Gauge(
            'bridge_liquidity_ratio',
            'Liquidity ratio (available / pending)',
            ['asset_type']
        )
        
        self.finalization_time = Histogram(
            'bridge_finalization_time_seconds',
            'Time to finalize claims',
            buckets=[60, 300, 600, 1800, 3600, 7200]  # 1min, 5min, 10min, 30min, 1h, 2h
        )
        
        self.gas_costs = Histogram(
            'bridge_gas_costs_wei',
            'Gas costs for operations',
            ['operation'],  # submit_claim, challenge, finalize
            buckets=[100000, 500000, 1000000, 2000000, 5000000]
        )
        
    def start_server(self):
        """Start Prometheus metrics server"""
        start_http_server(self.port)
        logger.info(f"Metrics server started on port {self.port}")
    
    def update_deposit(self, chain: str, asset: str):
        """Record a deposit"""
        self.deposits_total.labels(chain=chain, asset=asset).inc()
    
    def update_claim(self, status: str):
        """Record a claim"""
        self.claims_total.labels(status=status).inc()
    
    def update_challenge(self, result: str):
        """Record a challenge"""
        self.challenges_total.labels(result=result).inc()
    
    def update_bond(self, relayer: str, amount: int, slashed: bool = False):
        """Update bond metrics"""
        if slashed:
            self.bonds_slashed.labels(relayer=relayer).inc(amount)
        else:
            self.bonds_posted.labels(relayer=relayer).set(amount)
    
    def update_liquidity(self, asset_type: str, total: int, pending: int, available: int):
        """Update liquidity metrics"""
        self.liquidity_total.labels(asset_type=asset_type).set(total)
        self.liquidity_pending.labels(asset_type=asset_type).set(pending)
        self.liquidity_available.labels(asset_type=asset_type).set(available)
        
        if pending > 0:
            ratio = available / pending
            self.liquidity_ratio.labels(asset_type=asset_type).set(ratio)
    
    def record_finalization_time(self, seconds: float):
        """Record finalization time"""
        self.finalization_time.observe(seconds)
    
    def record_gas_cost(self, operation: str, gas_used: int, gas_price: int):
        """Record gas cost"""
        total_cost = gas_used * gas_price
        self.gas_costs.labels(operation=operation).observe(total_cost)


def main():
    """Main entry point"""
    exporter = MetricsExporter(port=8000)
    exporter.start_server()
    
    # Keep server running
    while True:
        time.sleep(1)


if __name__ == '__main__':
    main()

