from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
import uuid

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.name

class Channel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='channel')
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    handle = models.CharField(max_length=100, unique=True)
    thumbnail = models.ImageField(upload_to='channels/thumbnails/', blank=True, null=True)
    banner = models.ImageField(upload_to='channels/banners/', blank=True, null=True)
    subscribers = models.ManyToManyField(User, related_name='subscriptions', blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class Video(models.Model):
    TYPE_CHOICES = (
        ('standard', 'Standard'),
        ('short', 'Short'),
        ('live_recording', 'Live Recording'),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    channel = models.ForeignKey(Channel, on_delete=models.CASCADE, related_name='videos')
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    thumbnail = models.ImageField(upload_to='videos/thumbnails/')
    video_file = models.FileField(upload_to='videos/raw/', blank=True, null=True)
    hls_url = models.URLField(blank=True, null=True, help_text="S3/CloudFront HLS URL")
    views = models.PositiveIntegerField(default=0)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='videos')
    video_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='standard')
    is_published = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return self.title

class LiveStream(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    channel = models.ForeignKey(Channel, on_delete=models.CASCADE, related_name='live_streams')
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    thumbnail = models.ImageField(upload_to='live/thumbnails/')
    stream_key = models.CharField(max_length=100, unique=True, default=uuid.uuid4)
    is_live = models.BooleanField(default=False)
    viewer_count = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.channel.name} - {self.title}"
