from django.db import models
from app01.models import UserInfo


class DetectionFeedback(models.Model):
    SOURCE_CHOICES = [
        ('MULTI', '多模型实验室'),
        ('PAD', '病虫害检测'),
        ('SHAPE', '品相分级'),
    ]
    user = models.ForeignKey(UserInfo, on_delete=models.CASCADE, verbose_name="反馈用户")
    source_type = models.CharField(max_length=10, choices=SOURCE_CHOICES, verbose_name="来源功能")
    record_id = models.IntegerField(verbose_name="检测记录ID")

    is_correct = models.BooleanField(default=True, verbose_name="结果是否准确")
    correct_label = models.CharField(max_length=100, blank=True, verbose_name="纠正标签")
    comment = models.TextField(blank=True, verbose_name="补充说明")
    submit_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "检测反馈"
        verbose_name_plural = verbose_name


class SystemEvolutionLog(models.Model):

    image_path = models.CharField(max_length=255)
    pred_label = models.CharField(max_length=50)
    user_corrected_label = models.CharField(max_length=50, null=True, blank=True)
    is_correct = models.BooleanField(default=True)

    recorded_at = models.DateTimeField(auto_now_add=True)

    @classmethod
    def get_current_accuracy(cls):

        total = cls.objects.count()
        if total == 0: return 100.0
        corrects = cls.objects.filter(is_correct=True).count()
        return round((corrects / total) * 100, 2)

class EvolutionLog(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    is_correct = models.BooleanField(default=True)
    pred_label = models.CharField(max_length=50)
    user_label = models.CharField(max_length=50, null=True)

    @classmethod
    def get_evolution_data(cls):

        import datetime
        data = []
        for i in range(29, -1, -1):
            date = datetime.date.today() - datetime.timedelta(days=i)
            logs = cls.objects.filter(timestamp__date=date)
            total = logs.count()
            if total > 0:
                accuracy = (logs.filter(is_correct=True).count() / total) * 100
            else:
                accuracy = 100.0
            data.append({'date': date.strftime('%m-%d'), 'acc': round(accuracy, 2)})
        return data

class UserFeedback(models.Model):
    """小程序用户意见反馈表"""
    # 注意这里和你其他表一样，关联 app01 的 UserInfo
    user = models.ForeignKey(UserInfo, on_delete=models.CASCADE, null=True, blank=True, verbose_name="反馈用户")
    content = models.TextField(verbose_name="反馈内容")
    submit_time = models.DateTimeField(auto_now_add=True, verbose_name="提交时间")

    class Meta:
        verbose_name = "用户意见反馈"
        verbose_name_plural = verbose_name