"""
-----------------------------------
# Instructions for Code Execution
-----------------------------------

## Overview
This script uses OpenAI's GPT-3.5 Turbo model to summarize topics generated by Latent Dirichlet Allocation (LDA), specifically focusing on ESG content.

## Folder Structure
- The script is located in the 'Code' folder.
- Results are stored in the 'Results' folder within a file named 'ESG_Summary_Topics.xlsx'.

## Prerequisites
- Ensure the OpenAI API key is set in the `.env` file located in the base directory.
- Required libraries (`openai`, `pandas`, `python-dotenv`) must be installed.

## Processing Steps
1. **API Key Configuration**: Load the OpenAI API key from the `.env` file to authenticate API requests.
2. **Text Preparation**: Format the input topics text to be processed by GPT-3.5 Turbo.
3. **GPT Model Invocation**: Send the formatted text to the GPT-3.5 Turbo model and receive a summarized interpretation of LDA topics.
4. **Data Formatting and Storage**: The model's output is parsed into a list, then formatted into a DataFrame which is subsequently saved as an Excel file in the 'Results' folder.

## Output
- The summarized topics are saved in an Excel file named 'ESG_Summary_Topics.xlsx' located in the 'Results' folder.
- The script also prints the summary directly to the console for immediate review.

"""


import openai
import os
import pandas as pd
from dotenv import load_dotenv

#------------ Set up logging ------------ 
import log_config
log_config.setup_logging()
import logging
logging.info("Running script 'GPT Topic Modeling.py'")


#------------ Load OpenAI API Key from the environment ------------
# Load environment variables from .env file
load_dotenv()
# Set API key in the environment variables (.env file)
api_key = os.getenv("OPENAI_API_KEY")
openai.api_key = api_key

#------------ GPT Interpretation of Topic Modeling Results ------------

def summarize_document(prompt):
    response = openai.ChatCompletion.create(
        model='gpt-3.5-turbo',  # GPT-3.5 model
        messages = [{"role": "user", "content": prompt}],
        temperature=0.0
    )
    summary = response.choices[0].message["content"]
    return summary

text= f"""Topic 1: man | group | social | medium | information | term | page | use | institute | site | content | bank | may | governance | security | please | related | island | privacy | provided
Topic 2: ohjin | dukeun | overpopulation | artisanal | calgarians | certificationhomeownersour | criteriateamintermediariesmoreuse | investorsandfamily | inthenext | criteriateamintermediariesmorewhy | isunsustainable | thathasnot | homeownersour | ocif | gradation | centricity | bravery | tiktok | handmade | catalyse
Topic 3: company | energy | technology | team | investment | global | gas | group | renewable | green | operation | impact | packaging | oil | industry | food | fund | di | sustainability | year
Topic 4: sterling | investment | partner | service | business | management | equity | billion | value | transaction | company | north | energy | dakota | industry | capital | private | growth | including | work
Topic 5: cvc | esg | island | investment | investor | connecting | le | criterion | responsibly | fund | investing | sustainability | und | capital | de | saint | modern | slavery | community | du
Topic 6: affair | office | relation | employee | facility | community | academic | health | service | business | development | management | board | general | chancellor | audit | planning | regent | counsel | compliance
Topic 7: service | esg | equity | investment | sustainable | business | market | bbh | fund | community | partner | financial | company | security | investor | year | firm | private | inclusion | management
Topic 8: news | experience | community | partnership | login | approach | contact | investor | home | contacthome | internship | csl | read | series | healthcare | heron | cannabis | board | serf | capital
Topic 9: fund | shareholder | director | corporate | investment | share | financial | governance | meeting | performance | report | calendar | top | dividend | announcement | board | credit | distressed | opportunity | committee
Topic 10: investment | sustainable | fund | advisory | triton | private | client | management | manager | firm | equity | portfolio | company | esg | brown | investing | business | adviser | office | family
"""

prompt=f"""Summarise the given topics obtained from\
the Latent Dirichlet Allocation (LDA) algorithm in a meaningful way. Note that these topics have been\
obtained from the documents containing ESG content. Give ESG summary topics that are concise and \
assign the respective topics.\
\n\nHere is the text for your\
evaluation:\n ```{text}```"""  # Mention the prompt here to ChatGPT

summary = summarize_document(prompt)

# Split summary into a list of topics
summary_list = summary.strip().split('\n')

# Create a DataFrame
df = pd.DataFrame(summary_list, columns=['ESG Summary Topics'])

# Save the DataFrame to an Excel file
output_file_path = '../Results/ESG_Summary_Topics.xlsx'
df.to_excel(output_file_path, index=False)

print(f"Summary output has been saved to {output_file_path}")


print(summary)

#------------ Log completion of the script ------------
logging.info("Finished running 'GPT Topic Modeling.py'")