from django.db import models
from django.utils.translation import gettext_lazy as _

class OperationLog(models.Model):
    class OpType(models.TextChoices):
        STARTUP = 'startup', _('系统启动')
        REQUEST = 'request', _('HTTP请求')
        VIEW = 'view', _('视图处理')
        DB = 'db', _('数据库操作')
        CACHE = 'cache', _('缓存操作')
        CELERY = 'celery', _('异步任务')
        COMMAND = 'command', _('管理命令')
        SIGNAL = 'signal', _('信号处理')
        AUTH = 'auth', _('认证授权')
        EXCEPTION = 'exception', _('异常错误')
        CUSTOM = 'custom', _('自定义业务')

    # 基础信息
    id = models.BigAutoField(primary_key=True)
    trace_id = models.CharField(max_length=32, db_index=True, help_text="全链路唯一ID")
    parent_id = models.CharField(max_length=32, null=True, blank=True, help_text="父级操作ID")
    operation_type = models.CharField(max_length=20, choices=OpType.choices, db_index=True)
    level = models.CharField(max_length=10, default='INFO')  # DEBUG, INFO, WARNING, ERROR
    
    # 时间信息
    start_time = models.DateTimeField(db_index=True)
    end_time = models.DateTimeField(null=True, blank=True)
    duration = models.FloatField(help_text="耗时(ms)", null=True)

    # 用户上下文
    user_id = models.CharField(max_length=64, null=True, blank=True, db_index=True)
    username = models.CharField(max_length=150, null=True, blank=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    
    # 核心内容 (使用 JSONField 存储差异化数据)
    # 包含: method, path, sql, cache_key, view_func, params, exception_info 等
    details = models.JSONField(default=dict)
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(fields=['operation_type', 'created_at']),
            models.Index(fields=['user_id', 'created_at']),
        ]
        ordering = ['-created_at']
        verbose_name = _('操作日志')
        verbose_name_plural = _('操作日志')
