<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header("Content-Type:application/json;charset=utf-8");

// 改成宿主机IP
$host = "10.150.117.190";
$user = "root";
$pass = "hp93000";
$dbname = "alert_mail_stat";

$conn = mysqli_connect($host,$user,$pass,$dbname);
if (!$conn) {
    echo json_encode([
        "code" => 500,
        "msg" => "数据库连接失败：" . mysqli_connect_error()
    ], JSON_UNESCAPED_UNICODE);
    exit;
}
mysqli_set_charset($conn,"utf8mb4");

$rawBody = file_get_contents('php://input');
$alertData = json_decode($rawBody, true);

if (!is_array($alertData) || empty($alertData['alerts'])) {
    echo json_encode([
        "code" => 400,
        "msg" => "未获取到有效告警数据"
    ], JSON_UNESCAPED_UNICODE);
    mysqli_close($conn);
    exit;
}

$insertCount = 0;
foreach ($alertData['alerts'] as $alert) {
    $alertName  = mysqli_real_escape_string($conn, $alert['labels']['alertname'] ?? "未知告警");
    $instance   = mysqli_real_escape_string($conn, $alert['labels']['instance'] ?? "");
    $severity   = mysqli_real_escape_string($conn, $alert['labels']['severity'] ?? "warning");
    $status     = $alert['status'] ?? "firing";
    $startsAt   = mysqli_real_escape_string($conn, $alert['startsAt'] ?? date("Y-m-d H:i:s"));
    $endsAt     = isset($alert['endsAt']) ? "'" . mysqli_real_escape_string($conn, $alert['endsAt']) . "'" : "NULL";
    $fingerprint= mysqli_real_escape_string($conn, $alert['fingerprint'] ?? md5($alertName.$instance.$startsAt));
    $content    = mysqli_real_escape_string($conn, json_encode($alert, JSON_UNESCAPED_UNICODE));
    $alertType  = $status === "resolved" ? 2 : 1;

    $checkSql = "SELECT id FROM alert_log WHERE mail_uid = '$fingerprint'";
    $checkRes = mysqli_query($conn, $checkSql);
    if (mysqli_num_rows($checkRes) > 0) continue;

    $insertSql = "INSERT INTO alert_log 
    (mail_uid, alert_type, alert_name, instance, severity, starts_at, ends_at, content, receive_time)
    VALUES ('$fingerprint', $alertType, '$alertName', '$instance', '$severity', '$startsAt', $endsAt, '$content', NOW())";
    
    if (mysqli_query($conn, $insertSql)) $insertCount++;
}

echo json_encode([
    "code" => 200,
    "msg" => "告警处理完成",
    "insert_num" => $insertCount
], JSON_UNESCAPED_UNICODE);

mysqli_close($conn);
?>
