from django.db import models
from django.conf import settings
from django.utils import timezone
from datetime import timedelta

User = settings.AUTH_USER_MODEL

# Get expiry time from settings or use default (2 minutes)
STATUS_EXPIRY_SECONDS = getattr(settings, 'STATUS_EXPIRY_SECONDS', 120)


class Status(models.Model):
    """
    Status model - Auto-expires after STATUS_EXPIRY_SECONDS
    Similar to Instagram/WhatsApp stories
    """
    user = models.ForeignKey(
        User,
        related_name="statuses",
        on_delete=models.CASCADE
    )
    content = models.TextField(blank=True, null=True)
    media = models.FileField(
        upload_to="status/%Y/%m/%d/",
        blank=True,
        null=True,
        help_text="Image or video file"
    )
    media_type = models.CharField(
        max_length=10,
        choices=[
            ('image', 'Image'),
            ('video', 'Video'),
            ('text', 'Text Only'),
        ],
        default='text'
    )
    background_color = models.CharField(
        max_length=7,
        default='#667eea',
        help_text="Hex color for text-only status"
    )
    created_at = models.DateTimeField(default=timezone.now)
    expires_at = models.DateTimeField()

    class Meta:
        verbose_name = "Status"
        verbose_name_plural = "Statuses"
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['-created_at']),
            models.Index(fields=['user', '-created_at']),
            models.Index(fields=['expires_at']),
        ]

    def save(self, *args, **kwargs):
        # Auto-set expiry time if not set
        if not self.expires_at:
            self.expires_at = timezone.now() + timedelta(seconds=STATUS_EXPIRY_SECONDS)
        super().save(*args, **kwargs)

    def is_expired(self):
        """Check if status has expired"""
        return timezone.now() > self.expires_at

    def time_remaining(self):
        """Get remaining time in seconds"""
        if self.is_expired():
            return 0
        delta = self.expires_at - timezone.now()
        return int(delta.total_seconds())

    def __str__(self):
        return f"Status by {self.user.username} - {self.created_at}"


class StatusView(models.Model):
    """
    Track who viewed a status
    """
    status = models.ForeignKey(
        Status,
        related_name="views",
        on_delete=models.CASCADE
    )
    viewer = models.ForeignKey(
        User,
        related_name="status_views",
        on_delete=models.CASCADE
    )
    viewed_at = models.DateTimeField(default=timezone.now)

    class Meta:
        verbose_name = "Status View"
        verbose_name_plural = "Status Views"
        unique_together = ('status', 'viewer')
        ordering = ['-viewed_at']
        indexes = [
            models.Index(fields=['status', '-viewed_at']),
            models.Index(fields=['viewer', '-viewed_at']),
        ]

    def __str__(self):
        return f"{self.viewer.username} viewed {self.status.user.username}'s status"