from flask import Flask, request, jsonify
import pymysql

app = Flask(__name__)

def get_db():
    return pymysql.connect(
        host="127.0.0.1",
        user="root",
        password="hp93000",
        database="alert_mail_stat",
        charset="utf8mb4"
    )

@app.route("/alert", methods=["POST"])
def alert_in():
    raw = request.get_json()
    alerts = raw.get("alerts", [])
    add_cnt = 0
    db = get_db()
    cur = db.cursor()
    for alert in alerts:
        fp = alert["fingerprint"]
        alert_name = alert["labels"].get("alertname", "")
        instance = alert["labels"].get("instance", "")
        severity = alert["labels"].get("severity", "warning")
        status = alert["status"]
        start = alert.get("startsAt", "")
        end = alert.get("endsAt")
        type_val = 2 if status == "resolved" else 1

        cur.execute("SELECT id FROM alert_log WHERE mail_uid=%s", (fp,))
        if cur.fetchone():
            continue
        sql = """
        INSERT INTO alert_log(mail_uid,alert_type,alert_name,instance,severity,starts_at,ends_at,content,receive_time)
        VALUES(%s,%s,%s,%s,%s,%s,%s,%s,NOW())
        """
        cur.execute(sql, (fp, type_val, alert_name, instance, severity, start, end, str(alert)))
        add_cnt += 1
    db.commit()
    cur.close()
    db.close()
    return jsonify({"code": 200, "insert_count": add_cnt})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=909, debug=False)
