#!/usr/bin/env python3
"""Simple Docker metrics exporter for Prometheus"""
import docker
from prometheus_client import Gauge, Counter, generate_latest, CONTENT_TYPE_LATEST
from http.server import HTTPServer, BaseHTTPRequestHandler
import sys

# Métriques
container_cpu_usage = Gauge('docker_container_cpu_usage_seconds_total', 'CPU usage in seconds', ['container', 'image'])
container_memory_usage = Gauge('docker_container_memory_usage_bytes', 'Memory usage in bytes', ['container', 'image'])
container_network_rx = Counter('docker_container_network_receive_bytes_total', 'Network receive bytes', ['container', 'image'])
container_network_tx = Counter('docker_container_network_transmit_bytes_total', 'Network transmit bytes', ['container', 'image'])
container_status = Gauge('docker_container_status', 'Container status (1=running, 0=stopped)', ['container', 'image'])

client = docker.from_env()

class MetricsHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Mettre à jour les métriques
        for container in client.containers.list():
            name = container.name
            image = container.image.tags[0] if container.image.tags else 'unknown'
            
            try:
                stats = container.stats(stream=False)
                
                # CPU
                cpu_delta = stats['cpu_stats']['cpu_usage']['total_usage'] - stats['precpu_stats']['cpu_usage']['total_usage']
                system_delta = stats['cpu_stats']['system_cpu_usage'] - stats['precpu_stats']['system_cpu_usage']
                if system_delta > 0:
                    cpu_usage = (cpu_delta / system_delta) * stats['cpu_stats'].get('online_cpus', 1)
                    container_cpu_usage.labels(name, image).set(cpu_usage)
                
                # Memory
                mem_usage = stats['memory_stats']['usage']
                container_memory_usage.labels(name, image).set(mem_usage)
                
                # Network
                if 'networks' in stats:
                    for iface, data in stats['networks'].items():
                        container_network_rx.labels(name, image).inc(data.get('rx_bytes', 0))
                        container_network_tx.labels(name, image).inc(data.get('tx_bytes', 0))
                
                # Status
                container_status.labels(name, image).set(1 if container.status == 'running' else 0)
                
            except Exception as e:
                print(f"Error getting stats for {name}: {e}")
        
        # Exposer les métriques
        self.send_response(200)
        self.send_header('Content-Type', CONTENT_TYPE_LATEST)
        self.end_headers()
        self.wfile.write(generate_latest())
    
    def log_message(self, format, *args):
        pass  # Suppress logs

if __name__ == '__main__':
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8005
    server = HTTPServer(('0.0.0.0', port), MetricsHandler)
    print(f"Docker metrics exporter listening on port {port}")
    server.serve_forever()
