#!/usr/bin/env python3
import json
import requests

# UID de la datasource Prometheus (smart-city-prometheus-brokers)
# À récupérer via l'API Grafana
try:
    resp = requests.get('https://grafana.digitribe.fr/api/datasources', 
                        auth=('admin', 'Digitribe972'), verify=False)
    ds_uid = None
    if resp.ok:
        for ds in resp.json():
            if 'prometheus' in ds['type'].lower() and 'broker' in ds['name'].lower():
                ds_uid = ds['uid']
                print(f"Datasource Prometheus trouvée: {ds['name']} (UID: {ds_uid})")
                break
except:
    pass

if not ds_uid:
    ds_uid = 'f9ddd651-33ec-4dad-a950-e1375a964315'  # Fallback Prometheus Brokers
    print(f"Utilisation UID par défaut: {ds_uid}")

dashboard = {
    "annotations": {"list": []},
    "editable": True,
    "fiscalYearStartMonth": 0,
    "graphTooltip": 1,
    "id": None,
    "links": [],
    "panels": [
        # CPU Usage
        {
            "title": "CPU Usage (Docker Containers)",
            "type": "timeseries",
            "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
            "datasource": {"type": "prometheus", "uid": ds_uid},
            "targets": [
                {
                    "expr": 'rate(docker_container_cpu_usage_seconds_total[5m]) * 100',
                    "legendFormat": "{{container}}",
                    "refId": "A"
                }
            ],
            "fieldConfig": {
                "defaults": {
                    "unit": "percent"
                }
            }
        },
        # Memory Usage
        {
            "title": "Memory Usage (Docker Containers)",
            "type": "timeseries",
            "gridPos": {"h": 8, "w": 12, "x": 12, "y": 0},
            "datasource": {"type": "prometheus", "uid": ds_uid},
            "targets": [
                {
                    "expr": 'docker_container_memory_usage_bytes / 1024 / 1024 / 1024',
                    "legendFormat": "{{container}} (GB)",
                    "refId": "A"
                }
            ],
            "fieldConfig": {
                "defaults": {
                    "unit": "decbytes"
                }
            }
        },
        # Network Traffic (RX)
        {
            "title": "Network Receive (Docker Containers)",
            "type": "timeseries",
            "gridPos": {"h": 8, "w": 12, "x": 0, "y": 16},
            "datasource": {"type": "prometheus", "uid": ds_uid},
            "targets": [
                {
                    "expr": 'rate(docker_container_network_receive_bytes_total[5m]) * 8',
                    "legendFormat": "{{container}} RX",
                    "refId": "A"
                }
            ],
            "fieldConfig": {
                "defaults": {
                    "unit": "bps"
                }
            }
        },
        # Network Traffic (TX)
        {
            "title": "Network Transmit (Docker Containers)",
            "type": "timeseries",
            "gridPos": {"h": 8, "w": 12, "x": 12, "y": 16},
            "datasource": {"type": "prometheus", "uid": ds_uid},
            "targets": [
                {
                    "expr": 'rate(docker_container_network_transmit_bytes_total[5m]) * 8',
                    "legendFormat": "{{container}} TX",
                    "refId": "A"
                }
            ],
            "fieldConfig": {
                "defaults": {
                    "unit": "bps"
                }
            }
        },
        # Container Status
        {
            "title": "Container Status (1=Running, 0=Stopped)",
            "type": "state-timeline",
            "gridPos": {"h": 8, "w": 24, "x": 0, "y": 32},
            "datasource": {"type": "prometheus", "uid": ds_uid},
            "targets": [
                {
                    "expr": 'docker_container_status',
                    "legendFormat": "{{container}}",
                    "refId": "A"
                }
            ]
        }
    ],
    "schemaVersion": 38,
    "style": "dark",
    "tags": ["docker", "containers", "metrics", "prometheus"],
    "templating": {"list": []},
    "time": {"from": "now-1h", "to": "now"},
    "title": "Smart City - Docker Containers Metrics",
    "uid": "smartcity-docker-metrics",
    "version": 1
}

# Sauvegarder localement
with open('/home/eric/smart-city-digital-twin-martinique/grafana-dashboard-docker-metrics.json', 'w') as f:
    json.dump(dashboard, f, indent=2)

print("✅ Dashboard Docker Metrics généré")
print(f"   Fichier: grafana-dashboard-docker-metrics.json")
print(f"   UID: {dashboard['uid']}")
print(f"   Datasource Prometheus: {ds_uid}")
