import io
from openai import OpenAI
from flask import jsonify


#Sends the conversation to the summary agent and returns the result
def summary(bob, conversation):
    OPENAI_API_KEY = bob['OpenAI']['API_KEY']
    OPENAI_SUMMARY_ASSISTANT_ID = bob['OpenAI']['summary_id']

    summary_bot = OpenAI(api_key=OPENAI_API_KEY)
    summary_thread = summary_bot.beta.threads.create()
    summary_thread_id = summary_thread.id

    summary_message = summary_bot.beta.threads.messages.create(
        thread_id=summary_thread_id, role="user", content=conversation)

    summary_run = summary_bot.beta.threads.runs.create_and_poll(
        thread_id=summary_thread_id, assistant_id=OPENAI_SUMMARY_ASSISTANT_ID)
    summary_run_id = summary_run.id

    if not summary_thread_id or not summary_run_id:
        print("ERROR: Missing summary_thread_id or summary_run_id")
        return jsonify({"response": "error"})

    summary_run_status = summary_bot.beta.threads.runs.retrieve(
        thread_id=summary_thread_id, run_id=summary_run_id)

    if summary_run_status.status == 'completed':
        summary_messages = summary_bot.beta.threads.messages.list(
            thread_id=summary_thread_id)
        summary_message_content = summary_messages.data[0].content[0].text
        summary = summary_message_content.value

        # tokens = summary_run_status.usage
        tokens = summary_run_status.usage.total_tokens

        return summary


def upload_knowledge_base(bob, kb):
    OPENAI_API_KEY = bob['OpenAI']['API_KEY']
    OPENAI_MEMORY_ID = bob['OpenAI']['memory_id']
    BOB_ID = bob['OpenAI']['bob_id']

    memory_bot = OpenAI(api_key=OPENAI_API_KEY)

    memory_assistant = memory_bot.beta.assistants.retrieve(
        assistant_id=OPENAI_MEMORY_ID)

    vector_store = get_assistant_vector_store(memory_assistant,
                                              OPENAI_MEMORY_ID)
    if vector_store:
        delete_files(memory_bot, vector_store)

    kb_filename = f"{BOB_ID}.txt"
    upload_file_to_vector_store(memory_bot, vector_store,
                                "memories/" + kb_filename)

    # Convert the string into a file-like object
    #file_like_object = io.BytesIO(kb.encode("utf-8"))
    #file_like_object.name = kb_filename  # Add a name attribute for API compatibility

    print(
        f"New file '{BOB_ID}.txt' uploaded to vector store with updated contents."
    )

    return


def get_assistant_vector_store(client, assistant_id):
    if hasattr(client, 'tool_resources') and hasattr(client.tool_resources,
                                                     'file_search'):
        vector_store_ids = client.tool_resources.file_search.vector_store_ids
        if vector_store_ids:
            return vector_store_ids[0]  # Return the first vector store ID
        else:
            print("ERROR: No vector store IDs attached for: " + assistant_id)
    else:
        print("ERROR: No tool resources found for: " + assistant_id)


def delete_files(client, vector_store_id):
    # List all files in the vector store
    files = client.beta.vector_stores.files.list(vector_store_id)

    for file in files.data:
        file_id = file.id
        print(file_id)
        client.beta.vector_stores.files.delete(vector_store_id=vector_store_id,
                                               file_id=file_id)
        print(f"File '{file_id}' deleted from vector store.")
        client.files.delete(file_id)
        print(f"File '{file_id}' permanently deleted.")


def upload_file_to_vector_store(client, vector_store_id, file_path):
    # Open the file to be uploaded
    with open(file_path, "rb") as file_stream:
        # Upload the file and poll for completion
        file_batch = client.beta.vector_stores.file_batches.upload_and_poll(
            vector_store_id=vector_store_id, files=[file_stream])

        print(file_batch.status)
