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)

            # 1. 原有告警入库逻辑不变
            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

            # 2. 新增：同步监控规则，存在则置为启用1
            if alert_name:
                sync_rule_sql = """
                INSERT INTO monitor_rule (rule_name, status)
                VALUES (%s, 1)
                ON DUPLICATE KEY UPDATE status = 1
                """
                cur.execute(sync_rule_sql, [alert_name])

        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)
