<?php
session_start();
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,OPTIONS");
header("Access-Control-Allow-Headers: *");
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
    echo json_encode(array('code'=>0));
    exit;
}
$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    echo json_encode(array('code'=>401,'msg'=>'登录失效','list'=>array(),'total'=>0,'stat'=>array()));
    exit;
}
$_SESSION['login_time'] = time();

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

// 修复低版本PHP不支持 ?? 运算符，改用三元判断
$page = isset($_REQUEST['page']) ? (int)$_REQUEST['page'] : 1;
$pageSize = isset($_REQUEST['page_size']) ? (int)$_REQUEST['page_size'] : 20;
$startDate = isset($_REQUEST['start_date']) ? $_REQUEST['start_date'] : "";
$endDate = isset($_REQUEST['end_date']) ? $_REQUEST['end_date'] : "";
$filterMetric = isset($_REQUEST['metric']) ? trim($_REQUEST['metric']) : "";
$filterInstance = isset($_REQUEST['instance']) ? trim($_REQUEST['instance']) : "";
$filterGlobal = isset($_REQUEST['global']) ? trim($_REQUEST['global']) : "";
$distinct = isset($_REQUEST['distinct']) ? (int)$_REQUEST['distinct'] : 1;
$filterSeverity = isset($_REQUEST['severity']) ? $_REQUEST['severity'] : array();
$filterStatus = isset($_REQUEST['status']) ? $_REQUEST['status'] : array();
$isExport = (isset($_REQUEST['export']) && $_REQUEST['export'] == 1) ? 1 : 0;

$startTs = 0;
$endTs = 0;
if (!empty($startDate) && !empty($endDate)) {
    $startTs = strtotime($startDate);
    $endTs = strtotime($endDate . " 23:59:59");
} else {
    $today = date("Y-m-d");
    $startTs = strtotime($today);
    $endTs = strtotime($today . " 23:59:59");
}

$promQL = 'sort_desc(ALERTS)';
$params = array('query' => $promQL);
$params['start'] = $startTs;
$params['end'] = $endTs;
$params['step'] = 60;
$queryUrl = $promApi . "/query_range";
$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);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

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

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

$filterFunc = function ($row) use ($filterMetric, $filterInstance, $filterGlobal, $filterSeverity, $filterStatus) {
    if (!empty($filterGlobal)) {
        $g = strtolower($filterGlobal);
        $match = (stripos(strtolower($row['metric']), $g) !== false)
            || (stripos(strtolower($row['instance']), $g) !== false)
            || (stripos(strtolower($row['severity']), $g) !== false);
        if (!$match) return false;
    }
    if (!empty($filterMetric) && stripos($row['metric'], $filterMetric) === false) return false;
    if (!empty($filterInstance) && stripos($row['instance'], $filterInstance) === false) return false;
    if (!empty($filterSeverity) && !in_array($row['severity'], $filterSeverity)) return false;
    if (!empty($filterStatus) && !in_array($row['state'], $filterStatus)) return false;
    return true;
};
$rawAll = array_filter($rawAll, $filterFunc);
usort($rawAll, function($a, $b){
    return $b['timestamp'] - $a['timestamp'];
});

$listRaw = array();
$stat = array(
    'total_all' => count($rawAll),
    'total_firing' => 0,
    'total_resolved' => 0,
    'total_critical' => 0,
    'unique_count' => 0,
    'hour_data' => $hourCount
);
if ($distinct !== 1) {
    $listRaw = $rawAll;
    foreach ($rawAll as $r) {
        if ($r['state'] == 'firing') $stat['total_firing']++;
        else $stat['total_resolved']++;
        if ($r['severity'] == 'critical') $stat['total_critical']++;
    }
} else {
    $group = array();
    foreach ($rawAll as $row) {
        $key = md5($row['metric'] . "|" . $row['instance'] . "|" . $row['severity'] . "|" . $row['state']);
        if (!isset($group[$key])) {
            $group[$key] = array(
                'state' => $row['state'],
                'severity' => $row['severity'],
                'metric' => $row['metric'],
                'instance' => $row['instance'],
                'time' => $row['time'],
                'timestamp' => $row['timestamp'],
                'total_count' => 1,
                'labels' => $row['labels']
            );
        } else {
            $group[$key]['total_count']++;
            if ($row['timestamp'] > $group[$key]['timestamp']) {
                $group[$key]['time'] = $row['time'];
                $group[$key]['timestamp'] = $row['timestamp'];
            }
        }
    }
    $listRaw = array_values($group);
    $stat['unique_count'] = count($listRaw);
    foreach ($listRaw as $r) {
        if ($r['state'] == 'firing') $stat['total_firing']++;
        else $stat['total_resolved']++;
        if ($r['severity'] == 'critical') $stat['total_critical']++;
    }
}

$total = count($listRaw);
if ($isExport) {
    $pageData = $listRaw;
} else {
    $offset = ($page - 1) * $pageSize;
    $pageData = array_slice($listRaw, $offset, $pageSize);
}

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