#!/usr/bin/env python3
from flask import Flask, request
import json
import time
import requests

app = Flask(__name__)
LOKI_PUSH = "http://127.0.0.1:3100/loki/api/v1/push"

@app.route("/alert-relay", methods=["POST"])
def handle_alert():
    # 接收Alertmanager告警
    am_raw = request.get_json()
    # 转Loki标准推送格式
    payload = {
        "streams": [
            {
                "stream": {"job": "alertmanager"},
                "values": [
                    # 纳秒级时间戳 + 告警完整json字符串
                    [str(int(time.time() * 1000000000)), json.dumps(am_raw)]
                ]
            }
        ]
    }
    # 推送到Loki
    requests.post(LOKI_PUSH, json=payload)
    return "success", 200

if __name__ == "__main__":
    # 仅本地127.0.0.1监听9080，外部无法访问
    app.run(host="127.0.0.1", port=9081, debug=False)
