#!/usr/bin/env python3
from flask import Flask, jsonify
import requests

app = Flask(__name__)

ZABBIX_URL = "http://zabbix.comnet.mx/zabbix/api_jsonrpc.php"
ZABBIX_TOKEN = "651d262f3cbf4e38971134a0182f1627a64613ff4fc0e1f1e2fe2a53d92c19f9"

HEADERS = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {ZABBIX_TOKEN}"
}

def zabbix_api(method, params):
    payload = {
        "jsonrpc": "2.0",
        "method": method,
        "params": params,
        "id": 1
 }

    r = requests.post(ZABBIX_URL, json=payload, headers=HEADERS)
    data = r.json()

    # 🔴 Si hay error en Zabbix → mostrarlo
    if "error" in data:
        raise Exception(f"Zabbix API error: {data['error']}")

    return data["result"]

@app.route("/problems", methods=["GET"])
def get_problems():
    try:
        # 1. Problemas
        problems = zabbix_api("problem.get", {
            "output": ["eventid", "severity", "name", "objectid"],
            "severities": [4, 5],
            "recent": True
        })

        if not problems:
            return jsonify([])

        # 2. Trigger IDs
        triggerids = list({p["objectid"] for p in problems})

        # 3. Triggers → Hosts
        triggers = zabbix_api("trigger.get", {
            "output": ["triggerid"],
            "triggerids": triggerids,
            "selectHosts": ["hostid", "host"]
        })

        trigger_host_map = {}
        for t in triggers:
            trigger_host_map[t["triggerid"]] = t["hosts"]

        # 4. Host IDs
        hostids = list({
            h["hostid"]
            for hosts in trigger_host_map.values()
            for h in hosts
        })

        # 5. Hosts → IP
        hosts = zabbix_api("host.get", {
            "output": ["hostid", "host"],
            "hostids": hostids,
            "selectInterfaces": ["ip", "main"]
        })

        host_map = {}
        for h in hosts:
            ip = "N/A"
            for i in h.get("interfaces", []):
                if i["main"] == "1":
                    ip = i["ip"]
                    break
            host_map[h["hostid"]] = {
                "host": h["host"],
                "ip": ip
            }

        # 6. Resultado final
        result = []
        for p in problems:
            trigger_hosts = trigger_host_map.get(p["objectid"], [])

            for h in trigger_hosts:
                info = host_map.get(h["hostid"], {})
                result.append({
                    "host": info.get("host"),
                    "ip": info.get("ip"),
                    "severity": int(p["severity"]),
                    "problem": p["name"],
                    "eventid": p["eventid"]
                })

        return jsonify(result)

    except Exception as e:
        return jsonify({"error": str(e)})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5010)
