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

app = Flask(__name__)

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

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {TOKEN}"
}

@app.route("/hosts", methods=["GET"])
def get_hosts():

    payload = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": ["hostid", "host", "name", "status"],
            "selectInterfaces": ["ip", "dns", "port"],
            "selectProblems": ["eventid", "severity", "name"]
        },
        "id": 1
    }

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

    result = []

    for h in data.get("result", []):
        if h["interfaces"]:
            for i in h["interfaces"]:
                result.append({
                    "host": h["host"],
                    "name": h["name"],
                    "ip": i.get("ip"),
                    "dns": i.get("dns"),
                    "port": i.get("port"),
                    "status": "Enabled" if h["status"] == "0" else "Disabled",
                    "problem": True if h.get("problems") else False
                })

    return jsonify(result)

app.run(host="0.0.0.0", port=5000)
