import csv
import os

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
 
client = OpenAI()
 
def generate_description(model, producent, main_features, description):
    prompt = f"Model: {model}\nProducent: {producent}\nMain Features: {main_features}\nDescription: {description}\n\nGenerate a detailed product description:"
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
        {"role": "system", "content": "You are a helpful assistant designed to generate product descriptions."},
        {"role": "user", "content": f"Write a detailed product for max 150 characters description based on the following keyword:{prompt}."}
    ],
    max_tokens=150,
    temperature=0.5,
    )
    return response.choices[0].message.content.strip()
 
def read_csv_and_generate_descriptions(csv_file_path):
    # Read all rows from the CSV
    with open(csv_file_path, newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        fieldnames = reader.fieldnames.copy()
        rows = list(reader)
    
    # Add 'generation' to fieldnames if it doesn't exist
    if 'generation' not in fieldnames:
        fieldnames.append('generation')
    
    # Generate descriptions and add to rows
    for row in rows:
        generated_description = generate_description(row['model'], row['producent'], row['main features'], row['description'])
        row['generation'] = generated_description
        print(f"Generated Description for {row['model']}:\n{generated_description}\n")
    
    # Write back to the CSV file
    with open(csv_file_path, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)
    
    print(f"All descriptions have been generated and saved to '{csv_file_path}'")
 
# Usage
csv_file_path = './sample.csv'
read_csv_and_generate_descriptions(csv_file_path)