<?php
session_start();
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST,OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(json_encode(['code'=>0]));

$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    exit(json_encode(['code'=>401,'msg'=>'登录失效','list'=>[],'total'=>0]));
}
$_SESSION['login_time'] = time();

$promHost = "10.150.117.190";
$promPort = "9090";
$promApi = "http://{$promHost}:{$promPort}/api/v1";

$page = (int)($_REQUEST['page'] ?? 1);
$pageSize = (int)($_REQUEST['page_size'] ?? 20);
$filterDate = $_REQUEST['date'] ?? "";
$filterMetric = trim($_REQUEST['metric'] ?? "");
$filterSeverity = $_REQUEST['severity'] ?? "";
$filterStatus = $_REQUEST['status'] ?? "";
$distinct = (int)($_REQUEST['distinct'] ?? 1);

$promQL = 'sort_desc(ALERTS)';
$params = ['query' => $promQL];
if (!empty($filterDate)) {
    $end = strtotime($filterDate . " 23:59:59");
    $start = $end - 86400;
    $params['start'] = $start;
    $params['end'] = $end;
    $params['step'] = 60;
    $queryUrl = $promApi . "/query_range";
} else {
    $queryUrl = $promApi . "/query";
}

$url = $queryUrl . "?" . http_build_query($params);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$resp = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

if (!empty($err) || empty($resp)) {
    exit(json_encode([
        'code' => 500,
        'msg' => 'Prometheus连接失败:'.$err,
        'list' => [],
        'total' => 0
    ]));
}
$promData = json_decode($resp, true);
if ($promData['status'] !== 'success') {
    exit(json_encode([
        'code' => 500,
        'msg' => 'Prometheus查询异常',
        'list' => [],
        'total' => 0
    ]));
}

$rawAll = [];
if (!empty($promData['data']['result'])) {
    foreach ($promData['data']['result'] as $item) {
        $metric = $item['metric'];
        $state = $metric['alertstate'] ?? "";
        $sev = $metric['severity'] ?? "info";
        $alertName = $metric['alertname'] ?? "";
        $inst = $metric['instance'] ?? "";
        $values = $item['values'] ?? [];
        foreach ($values as $v) {
            $ts = (int)$v[0];
            $dt = date("Y-m-d H:i:s", $ts);
            $rawAll[] = [
                'state' => $state,
                'severity' => $sev,
                'metric' => $alertName,
                'instance' => $inst,
                'time' => $dt,
                'timestamp' => $ts
            ];
        }
    }
}

// ==========修复过滤逻辑==========
if (!empty($filterMetric)) {
    $rawAll = array_filter($rawAll, function($r) use ($filterMetric){
        return stripos($r['metric'], $filterMetric) !== false;
    });
}
if (!empty($filterSeverity)) {
    $rawAll = array_filter($rawAll, fn($r) => $r['severity'] === $filterSeverity);
}
if (!empty($filterStatus)) {
    $rawAll = array_filter($rawAll, fn($r) => $r['state'] === $filterStatus);
}

usort($rawAll, fn($a,$b) => $b['timestamp'] - $a['timestamp']);

if ($distinct !== 1) {
    $list = $rawAll;
} else {
    $group = [];
    foreach ($rawAll as $row) {
        $key = md5($row['metric'] . "|" . $row['instance'] . "|" . $row['severity'] . "|" . $row['state']);
        if (!isset($group[$key])) {
            $group[$key] = [
                'state' => $row['state'],
                'severity' => $row['severity'],
                'metric' => $row['metric'],
                'instance' => $row['instance'],
                'time' => $row['time'],
                'timestamp' => $row['timestamp'],
                'total_count' => 1
            ];
        } else {
            $group[$key]['total_count']++;
            if ($row['timestamp'] > $group[$key]['timestamp']) {
                $group[$key]['time'] = $row['time'];
                $group[$key]['timestamp'] = $row['timestamp'];
            }
        }
    }
    $list = array_values($group);
}

$total = count($list);
$offset = ($page - 1) * $pageSize;
$pageData = array_slice($list, $offset, $pageSize);

echo json_encode([
    'code' => 0,
    'msg' => 'ok',
    'total' => $total,
    'list' => $pageData
], JSON_UNESCAPED_UNICODE);
exit;
?>
