import glob
import os
import json
import time
from typing import NAME_1
import tkinter as tk
from tkinter import filedialog, messagebox
import sqlite3
import openai
import logging
from pygments.lexers import get_lexer_for_filename


class CodeCommentGenerator:
    def __init__(self, folder_path: str,
                 model_name: str,
                 api_key: str,
                 prompt: str = "Jesteś pomocnym asystentem."):
        self.folder_path = folder_path
        self.model_name = model_name
        self.prompt = prompt
        self.api_key = api_key
        self.comments = []
        self.conn = self.create_connection()
        self.create_table()
        self.setup_logging()

    def create_connection(self):
        # Creates a connection to the SQLite database
        conn = None
        try:
            conn = sqlite3.connect('comments.db')
            print(f'Successfully connected to SQLite database version {sqlite3.version}')
        except sqlite3.Error as e:
            print(f'An error occurred {e}')
        return conn

    def create_table(self):
        # Creates a table in the database if it doesn't exist
        cursor = self.conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS comments (
              id INTEGER PRIMARY KEY AUTOINCREMENT,
              file_path TEXT UNIQUE,
              comments TEXT,
              code TEXT,
              file_summary TEXT,
              user_inputs TEXT
            )
        """)
        self.conn.commit()

    def close_connection(self):
        # Closes the database connection if it exists
        if self.conn:
            self.conn.close()

    def setup_logging(self):
        # Setup logging configuration
        logging.basicConfig(filename='communication.log', filemode='a', level=logging.INFO)
        self.log = logging.getLogger("communication")

    def generate_comments(self, code: str, language: str) -> str:
        openai.api_key = self.api_key
        max_token_limit = 4096  # Maximum token limit for the model
        if len(code) > max_token_limit:
            code = code[:max_token_limit]  # Truncate the code if it exceeds the limit

        self.log.info(f"Sending message: Explain this {language} code: {code}")

        retries = 0
        max_retries = 5
        delay = 1  # Initial delay in seconds

        while retries < max_retries:
            try:
                response = openai.ChatCompletion.create(
                    model=self.model_name,
                    messages=[
                        {"role"