from django.db import models
from django.utils import timezone


class ThreatScan(models.Model):
    class ScanType(models.TextChoices):
        URL = "url", "URL / Website"
        MESSAGE = "message", "Email / Message"

    class RiskLevel(models.TextChoices):
        LOW = "low", "Low"
        MEDIUM = "medium", "Medium"
        HIGH = "high", "High"
        CRITICAL = "critical", "Critical"

    scan_type = models.CharField(max_length=20, choices=ScanType.choices)
    target_preview = models.CharField(max_length=220, help_text="Sanitized preview only; raw sensitive content is not stored.")
    content_hash = models.CharField(max_length=64, db_index=True)
    risk_score = models.PositiveSmallIntegerField(default=0)
    risk_level = models.CharField(max_length=20, choices=RiskLevel.choices, default=RiskLevel.LOW)
    verdict = models.CharField(max_length=160)
    explanation = models.TextField()
    indicators = models.JSONField(default=list, blank=True)
    recommended_actions = models.JSONField(default=list, blank=True)
    model_version = models.CharField(max_length=40, default="heuristic-nlp-v1")
    store_metadata = models.BooleanField(default=True)
    created_at = models.DateTimeField(default=timezone.now, db_index=True)

    class Meta:
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["scan_type", "risk_level"]),
            models.Index(fields=["created_at"]),
        ]

    def __str__(self):
        return f"{self.get_scan_type_display()} · {self.risk_score}/100 · {self.target_preview[:50]}"

    @property
    def risk_badge_class(self):
        return {
            self.RiskLevel.LOW: "success",
            self.RiskLevel.MEDIUM: "warning",
            self.RiskLevel.HIGH: "danger",
            self.RiskLevel.CRITICAL: "critical",
        }.get(self.risk_level, "secondary")
