import os
import random
import string
from django.db import models
from django.utils import timezone
from django.utils.text import slugify

class Video(models.Model):
    VIDEO_TYPES = [
        ('general', 'General'),
        ('hca', 'HCA'),
    ]

    title = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, blank=True)
    thumbnail = models.ImageField(upload_to='thumbnails/')
    video_file = models.FileField(upload_to='videos/')
    duration = models.CharField(max_length=20, blank=True)  # Manual entry for duration
    video_type = models.CharField(max_length=10, choices=VIDEO_TYPES, default='general')

    def save(self, *args, **kwargs):
        # Generate slug if not already present
        if not self.slug:
            self.slug = ''.join(random.choices(string.ascii_letters + string.digits, k=8))

        # Save the model normally, without auto-generating the duration
        super().save(*args, **kwargs)

    def __str__(self):
        return self.title


class Candidate(models.Model):
    CANDIDATE_TYPES = [
        ('general', 'General'),
        ('hca', 'HCA'),
    ]

    danone_id = models.CharField(max_length=100, unique=True)
    full_name = models.CharField(max_length=255)
    candidate_type = models.CharField(max_length=10, choices=CANDIDATE_TYPES, default='general')  # New field for type

    def __str__(self):
        return self.full_name


class CandidateVideoProgress(models.Model):
    candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE)
    video = models.ForeignKey(Video, on_delete=models.CASCADE)
    watched = models.BooleanField(default=False)
    watched_at = models.DateTimeField(null=True, blank=True)

    def mark_watched(self):
        self.watched = True
        self.watched_at = timezone.now()  # Use timezone.now() directly
        self.save()

    def __str__(self):
        return f"{self.candidate.full_name} - {self.video.title}"
