from django.db import models
from django.contrib.auth.models import User
from PIL import Image
import os

class Category(models.Model):
    name = models.CharField(max_length=100, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name_plural = "categories"
        ordering = ['name']
    
    def __str__(self):
        return self.name

class Album(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    cover_photo = models.ForeignKey('Photo', on_delete=models.SET_NULL, null=True, blank=True, related_name='album_covers')
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title
    
    @property
    def photo_count(self):
        return self.photos.count()

class Photo(models.Model):
    title = models.CharField(max_length=200, blank=True)
    image = models.ImageField(upload_to='photos/')
    thumbnail = models.ImageField(upload_to='thumbnails/', blank=True)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
    albums = models.ManyToManyField(Album, related_name='photos', blank=True)
    is_favorite = models.BooleanField(default=False)
    width = models.IntegerField(default=0)
    height = models.IntegerField(default=0)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-uploaded_at']
    
    def save(self, *args, **kwargs):
        if self.image and not self.width:
            try:
                img = Image.open(self.image)
                self.width, self.height = img.size
            except:
                pass
                
        super().save(*args, **kwargs)
        if self.image and not self.thumbnail:
            self.create_thumbnail()
    
    def create_thumbnail(self):
        if not self.image:
            return
        
        try:
            img = Image.open(self.image.path)
            img.thumbnail((300, 300), Image.Resampling.LANCZOS)
            
            thumb_name = f"thumb_{os.path.basename(self.image.name)}"
            thumb_path = os.path.join('media/thumbnails', thumb_name)
            
            os.makedirs(os.path.dirname(thumb_path), exist_ok=True)
            img.save(thumb_path, 'JPEG', quality=85)
            
            self.thumbnail = f'thumbnails/{thumb_name}'
            super().save(update_fields=['thumbnail'])
        except Exception as e:
            print(f"Error creating thumbnail: {e}")
    
    def __str__(self):
        return self.title or f"Photo {self.id}"