from django.db import models
from account.models import User
from product.models import ProductModel
from django.conf import settings
import openai
from time import sleep
from product.serializers import ProductChatSerializer


ASSISTANT_ID = 'asst_1wOnCKncEHkOfp0FjOIz4Xkp'
class ProductChatModel(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(ProductModel, on_delete=models.CASCADE)
    thread = models.CharField(max_length=400, blank=True, null=True)
    
    class Meta:
        unique_together = ['user', 'product']

    def __str__(self):
        return f'{self.user} - {self.product}'

    def save(self, *args, **kwargs):
        if not self.thread:  
            client = openai.OpenAI(api_key=settings.OPENAI_API_KEY)  
            product_json = ProductChatSerializer(instance=self.product).data
            print(product_json)
            try:
                
                thread = client.beta.threads.create(
                    messages=[
                        {
                            "role": "user",
                            #TODO update first message 
                            "content": f"this is the start of the chat greet the user this chat is about the product with given detail: {product_json}",
                        }
                    ]
                )

                
                run = client.beta.threads.runs.create(
                    thread_id=thread.id, 
                    assistant_id=ASSISTANT_ID
                )
                
                
                while run.status != "completed":
                    run = client.beta.threads.runs.retrieve(
                        thread_id=thread.id, 
                        run_id=run.id
                    )
                    sleep(1)

                
                self.thread = thread.id

            except Exception as e:
                print(f'error in chat class: {e}')
                raise ValueError(f"Error creating OpenAI thread: {e}")

        super().save(*args, **kwargs)