# models.py
from django.db import models
from django.contrib.postgres.fields import JSONField

class Product(models.Model):
    title = models.CharField(max_length=500)
    description = models.TextField()
    short_description = models.TextField(blank=True)
    attributes_extracted = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'products'
        indexes = [
            models.Index(fields=['attributes_extracted', 'created_at']),
        ]

class ProductImage(models.Model):
    product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField(upload_to='products/')
    order = models.PositiveIntegerField(default=0)
    
    class Meta:
        db_table = 'product_images'
        ordering = ['order']

class ProductAttribute(models.Model):
    product = models.ForeignKey(Product, related_name='attributes', on_delete=models.CASCADE)
    attribute_name = models.CharField(max_length=100, db_index=True)
    attribute_value = models.TextField()
    confidence_score = models.FloatField(default=0.0)
    extraction_method = models.CharField(
        max_length=20,
        choices=[('nlp', 'NLP'), ('llm', 'LLM'), ('hybrid', 'Hybrid')],
        default='hybrid'
    )
    needs_review = models.BooleanField(default=False)
    reviewed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'product_attributes'
        unique_together = ['product', 'attribute_name']
        indexes = [
            models.Index(fields=['attribute_name', 'confidence_score']),
            models.Index(fields=['needs_review', 'reviewed']),
        ]
    
    def save(self, *args, **kwargs):
        # Auto-flag low confidence for review
        if self.confidence_score < 0.7:
            self.needs_review = True
        super().save(*args, **kwargs)
