import os
from dotenv import load_dotenv
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
import glob

load_dotenv()
api_key=os.environ['OPENAI_API_KEY']

#質問に対して、求人番号と参考ドキュメントを返す
def retreive_job_id_and_documents(question, model="text-embedding-3-small"):
    try:
        current_directory = os.path.dirname(os.path.abspath(__file__))
        vector_store_file = f"{current_directory}/../../../data/vector_store/all_company_info_with_metadata"
        vectorstore = FAISS.load_local(
            vector_store_file,
            embeddings=OpenAIEmbeddings(model=model),
            allow_dangerous_deserialization=True)

        search_results = vectorstore.similarity_search(question, k=40)
        
        #質問から該当データに対して、Retreive実施→input documentsとjob_idの取得
        job_id = [result.metadata['job_id'] for result in search_results]
        input_documents = [result.page_content for result in search_results]
        
        # レスポンスのフォーマットを指定の形式に整える
        response_data = {
            "status": 200,
            "response": [
                {"job_id": int(job_id[i]), "input_documents": input_documents[i]}
                for i in range(len(job_id))
            ]
        }
        
        # 最終レスポンス
        print(response_data)
        return response_data
        
    
    except Exception as e:
        print(e)
        return "Something is wrong."



#質問に対して/var/www/html/zoom/staging/file/vector_db/all_company_infoのデータをRetrievalを実施。
def create_documents(question):
    try:
        current_directory = os.path.dirname(os.path.abspath(__file__))
        vector_store_file = f"{current_directory}/../../../data/vector_store/all_company_info"
        vectorstore = FAISS.load_local(
            vector_store_file,
            embeddings=OpenAIEmbeddings(),
            allow_dangerous_deserialization=True)

        docs = vectorstore.similarity_search(question, k=15)
        
        input_documents = str()
        
        for d in docs:
            input_documents += "input_documents: {}\n".format(d.page_content.replace('\n', ''))
                
        answer =f"""【質問】{question}
下記のinput documentsを参考にしながら、上記の質問への回答をお願いします。
【input documents】{input_documents}"""

        return answer
    
    except Exception as e:
        print(e)
        return "ごめんなさい。。何か問題が起きたようです。。"

#質問に対して/var/www/html/zoom/staging/file/vector_db/all_company_infoのデータをRetrievalを実施。
def create_docs_from_partial_company_info(question):
    try:
        current_directory = os.path.dirname(os.path.abspath(__file__))
        vector_store_file = f"{current_directory}/../../../data/vector_store/partial_company_info"
        vectorstore = FAISS.load_local(
            vector_store_file,
            embeddings=OpenAIEmbeddings(),
            allow_dangerous_deserialization=True)

        docs = vectorstore.similarity_search(question, k=15)
        
        input_documents = str()
        
        for d in docs:
            input_documents += "input_documents: {}\n".format(d.page_content.replace('\n', ''))
                
        answer =f"""【質問】{question}
下記のinput documentsを参考にしながら、上記の質問への回答をお願いします。
【input documents】{input_documents}"""

        return answer
    
    except Exception as e:
        print(e)
        return "ごめんなさい。。何か問題が起きたようです。。"


def retreive_company_info_by_id(job_id, question, model="text-embedding-3-small"):
    try:
        current_directory = os.path.dirname(os.path.abspath(__file__))
        vector_store_file_partial = f"{current_directory}/../../../data/vector_store/company_info_by_id/{job_id}_*"


        # {job_id}_ で始まるファイルを探す
        matching_files = glob.glob(vector_store_file_partial)
        
        if matching_files:
            vector_store_file = matching_files[0]
            vectorstore = FAISS.load_local(
                vector_store_file,
                embeddings=OpenAIEmbeddings(model=model),
                allow_dangerous_deserialization=True)
            
            docs = vectorstore.similarity_search(question, k=20)
            input_documents = str()
            for d in docs:
                input_documents += "input_documents: {}\n".format(d.page_content.replace('\n', ''))
                
            answer =f"""【質問】{question}
    下記のinput documentsを参考にしながら、上記の質問への回答をお願いします。
    【input documents】{input_documents}"""

            #print(answer)
            return answer
        
        else:
            print(f"No files found matching pattern: {vector_store_file_partial}")

    
    except Exception as e:
        print(e)
        return "ごめんなさい。。何か問題が起きたようです。。"

# job_id = 471
# company_name = "株式会社インテリジェントフォース"
# question = "組織文化について教えて。"
# retreive_company_info_by_id(job_id,company_name,question)

def vectordb_create_only_input_documents(question):
    try:
        current_directory = os.path.dirname(os.path.abspath(__file__))
        vector_store_file = f"{current_directory}/../file/vector_db/all_company_info"
        vectorstore = FAISS.load_local(
            vector_store_file,
            embeddings=OpenAIEmbeddings(),
            allow_dangerous_deserialization=True)

        docs = vectorstore.similarity_search(question, k=20)

        return docs
    
    except Exception as e:
        print(e)
        return "ごめんなさい。。何か問題が起きたようです。。"
    
# スクリプトが直接実行されたときのみ実行
if __name__ == "__main__":
    question = "海外で働ける企業は？"
    retreive_job_id_and_documents(question, model="text-embedding-3-small")