from django.db import models
import os, errno
from api.utils import SYSTEMPERFORMANCE, PROCESSPERFORMANCE

from api.utils import *
alertLever = [
    ('system', '系统级'),
    ('process', '进程级'),
]
alertMetric = [
    ('cpu', 'cpu使用率'),
    ('mem', '内存占用'),
    ('disk', '硬盘占用')
]
alertHandle = [
    ('noAction', '不做处理'),
    ('closeLatest', '关闭最新进程'),
    ('closeHighestCpu', '关闭CPU占用最高进程'),
    ('closeHighestMem', '关闭MEM占用最高进程'),
]
alertState = [
    ('enable', '启用'),
    ('disable', '未启用'),
]

class AlertManager(models.Manager):
    def checkAlert(self):
        triggeredAlert = []
        for alert in self.get_queryset().filter(state='enable'):
            print(SYSTEMPERFORMANCE)
            # 系统级检测
            if alert.level == 'system':
                if alert.metric == 'cpu' and alert.threshold <= float(SYSTEMPERFORMANCE['cpu']):
                    triggeredAlert.append(alert)
                if alert.metric == 'mem' and alert.threshold <= float(SYSTEMPERFORMANCE['mem_used']):
                    triggeredAlert.append(alert)
                if alert.metric == 'disk' and alert.threshold <= float(SYSTEMPERFORMANCE['disk_used']):
                    triggeredAlert.append(alert)
            # 进程级检测，遍历所有活跃进程，检查性能占用
            if alert.level == 'process':
                # PROCESSPERFORMANCE结构应为：
                # cpu、mem_used
                for pid in PROCESSPERFORMANCE:
                    if alert.metric == 'cpu' and alert.threshold <= float(PROCESSPERFORMANCE[pid]['cpu']):
                        triggeredAlert.append(alert)
                    if alert.metric == 'mem' and alert.threshold <= float(PROCESSPERFORMANCE[pid]['mem']):
                        triggeredAlert.append(alert)
        return triggeredAlert

    

class Alert(models.Model):
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)

    name = models.CharField(default="未命名告警规则", max_length=64, unique=True)
    level = models.CharField(choices=alertLever, default='system', max_length=16)
    # 监控指标
    metric = models.CharField(choices=alertMetric, default='cpu', max_length=16)
    # 触发阈值
    threshold = models.FloatField()

    handle = models.CharField(choices=alertHandle, default='noAction', max_length=16)

    state = models.CharField(choices=alertState, default='disable', max_length=16)



    objects = AlertManager()

    class Meta:
        app_label = 'api'
