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_receive():
    try:
        data = request.get_json()
        alerts = data.get("alerts", [])
        insert_num = 0
        update_num = 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_at = alert.get("startsAt", "")
            end_at = alert.get("endsAt")
            alert_type = 2 if status == "resolved" else 1
            content_str = str(alert)

            cur.execute("""
                SELECT id FROM alert_log 
                WHERE mail_uid=%s AND DATE(receive_time) = CURDATE() 
                ORDER BY id DESC LIMIT 1
            """, (fp,))
            row = cur.fetchone()

            if status == "resolved":
                if row:
                    cur.execute("""
                        UPDATE alert_log 
                        SET alert_type=%s, ends_at=%s, content=%s 
                        WHERE mail_uid=%s AND id=%s
                    """, (alert_type, end_at, content_str, fp, row[0]))
                    update_num += 1
            else:
                # 删掉唯一索引后，每次故障直接插入，不再判断是否存在
                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, alert_type, alert_name, instance, severity, start_at, end_at, content_str))
                insert_num += 1

        db.commit()
        cur.close()
        db.close()
        return jsonify({"code": 200, "insert": insert_num, "update": update_num})

    except Exception as e:
        if "db" in locals():
            db.rollback()
            db.close()
        return jsonify({"code": 500, "msg": str(e)}), 200

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