#import openai
import g4f
import os
from dotenv import load_dotenv
from tkinter import Tk, filedialog, Button, Label
from tqdm import tqdm
import csv
import subprocess
import sys

# Автоматическая установка отсутствующих пакетов
def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

required_packages = ["openai", "python-dotenv", "tqdm"]
for package in required_packages:
    try:
        __import__(package)
    except ImportError:
        install(package)

#load_dotenv('key.gpt')
#openai.api_key = os.getenv('OPENAI_API_KEY')

def format_prompt_for_openai(text):
    # Формирование текста для OpenAI в соответствии с предоставленным алгоритмом
    prompt = (
        "Analyze the following text to generate image metadata using the universal algorithm for creating metadata.\n"
        "1. Identify key objects, actions, and background elements.\n"
        "2. Note the primary colors and thematic aspects.\n"
        "3. Determine the target audience and potential usage.\n"
        "4. Create a title that is a complete sentence (at least 7 words, max 120 characters).\n"
        "5. Create a description under 200 characters, detailing usage and characteristics.\n"
        "6. Generate 30 to 49 keywords ranked by importance.\n"
        "Make sure to follow this output format:\n"
        "Title: <Title here>\n"
        "Description: <Description here>\n"
        "Keywords: <Comma-separated list of keywords>\n\n"
        "Text for analysis:\n" + text
    )
    return prompt

def process_file(text_file, directory, csv_writer):
    file_name_base = os.path.splitext(os.path.basename(text_file))[0]
    image_file = get_corresponding_image(file_name_base, directory)

    if not image_file:
        print(f"No corresponding image found for {text_file}, skipping.")
        return

    with open(text_file, "r", encoding="utf-8") as file:
        text = file.read()

    prompt = format_prompt_for_openai(text)

    try:
        #   model="gpt-4",
        #    messages=[
        
        from g4f.client import Client

client = Client()
response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "system", "content": "You analyze text to create metadata for images."},
                {"role": "user", "content": prompt}
            ]
        )

        analysis = response['choices'][0]['message']['content'].strip()
        print(f'Metadata analysis generated for {text_file}: {analysis}')

        # Извлекаем метаданные из текста в заданном формате
        title = description = keywords = ""
        
        # Обработка ответа в нужном формате
        for line in analysis.splitlines():
            if line.lower().startswith("title:"):
                title = line[len("title:"):].strip()
            elif line.lower().startswith("description:"):
                description = line[len("description:"):].strip()
            elif line.lower().startswith("keywords:"):
                keywords = line[len("keywords:"):].strip()

        # Проверка на наличие обязательных элементов
        if not title or not description or not keywords:
            print(f'Error: Missing metadata for {text_file}. Analysis result was: {analysis}')
        else:
            csv_writer.writerow([os.path.basename(image_file), title, description, keywords])

    except Exception as e:
        print(f"An error occurred while processing {text_file}: {e}")

def get_corresponding_image(file_name_base, directory):
    for ext in ['.jpeg', '.jpg', '.png']:
        img_path = os.path.join(directory, file_name_base + ext)
        if os.path.isfile(img_path):
            return img_path
    return None

def process_files():
    file_paths = filedialog.askopenfilenames(title="Select text files", filetypes=[("Text files", "*.txt")])
    directory = os.path.dirname(file_paths[0])
    csv_file_path = os.path.join(directory, 'metadata.csv')

    with open(csv_file_path, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(['Filename', 'Title', 'Description', 'Keywords'])

        progress = tqdm(total=len(file_paths), desc="Processing files")
        for text_file in file_paths:
            process_file(text_file, directory, writer)
            progress.update(1)
        progress.close()

    print(f'Metadata CSV created at: {csv_file_path}')

def process_directory():
    directory = filedialog.askdirectory(title="Select a directory")
    text_files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.txt')]
    csv_file_path = os.path.join(directory, 'metadata.csv')

    with open(csv_file_path, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(['Filename', 'Title', 'Description', 'Keywords'])

        progress = tqdm(total=len(text_files), desc="Processing files")
        for text_file in text_files:
            process_file(text_file, directory, writer)
            progress.update(1)
        progress.close()

    print(f'Metadata CSV created at: {csv_file_path}')

# Настройка графического интерфейса с помощью Tkinter
root = Tk()
root.title("Metadata Generator")

Label(root, text="Select files or directory for processing").pack()
Button(root, text="Select Files", command=process_files).pack()
Button(root, text="Select Directory", command=process_directory).pack()
root.mainloop()