<?php

declare(strict_types=1);

namespace Kylin\ElderlyCare\Standards;

/**
 * 健康数据异常检测标准
 * 基于 MZ/T 171 养老机构服务安全规范
 */
final class HealthAbnormalDetector
{
    /**
     * 检测体征数据是否异常
     * @return array{is_abnormal: bool, level: string, items: array}
     */
    public static function detect(array $data): array
    {
        $abnormalItems = [];
        $maxLevel = 'normal';

        // 血压检测
        if (isset($data['systolic'])) {
            if ($data['systolic'] >= 180 || $data['systolic'] <= 90) {
                $abnormalItems[] = 'systolic';
                $maxLevel = 'critical';
            } elseif ($data['systolic'] >= 160 || $data['systolic'] <= 100) {
                $abnormalItems[] = 'systolic';
                $maxLevel = $maxLevel === 'normal' ? 'warning' : $maxLevel;
            }
        }

        if (isset($data['diastolic'])) {
            if ($data['diastolic'] >= 110 || $data['diastolic'] <= 50) {
                $abnormalItems[] = 'diastolic';
                $maxLevel = 'critical';
            } elseif ($data['diastolic'] >= 100 || $data['diastolic'] <= 60) {
                $abnormalItems[] = 'diastolic';
                $maxLevel = $maxLevel === 'normal' ? 'warning' : $maxLevel;
            }
        }

        // 心率检测
        if (isset($data['heart_rate'])) {
            if ($data['heart_rate'] >= 150 || $data['heart_rate'] <= 40) {
                $abnormalItems[] = 'heart_rate';
                $maxLevel = 'critical';
            } elseif ($data['heart_rate'] >= 120 || $data['heart_rate'] <= 50) {
                $abnormalItems[] = 'heart_rate';
                $maxLevel = $maxLevel === 'normal' ? 'warning' : $maxLevel;
            }
        }

        // 血氧检测
        if (isset($data['blood_oxygen'])) {
            if ($data['blood_oxygen'] <= 85) {
                $abnormalItems[] = 'blood_oxygen';
                $maxLevel = 'critical';
            } elseif ($data['blood_oxygen'] <= 90) {
                $abnormalItems[] = 'blood_oxygen';
                $maxLevel = $maxLevel === 'normal' ? 'warning' : $maxLevel;
            }
        }

        // 体温检测
        if (isset($data['temperature'])) {
            if ($data['temperature'] >= 40 || $data['temperature'] <= 35) {
                $abnormalItems[] = 'temperature';
                $maxLevel = 'critical';
            } elseif ($data['temperature'] >= 38.5 || $data['temperature'] <= 36) {
                $abnormalItems[] = 'temperature';
                $maxLevel = $maxLevel === 'normal' ? 'warning' : $maxLevel;
            }
        }

        return [
            'is_abnormal' => !empty($abnormalItems),
            'level' => $maxLevel,
            'items' => $abnormalItems,
        ];
    }
}
