from app.utils.extra import run_code
from app.config.application import settings
from app.schemas.chat_schema import factCode
from app.utils.prompts import fact_prompt

from langchain_openai.chat_models.base import ChatOpenAI


async def fact_report(standaloneQuestion:str, date:str, callbacks=None, **kwargs):
    
    data = None
    factData = ''
    
    # LLM for answer user query from fact files.
    llm = ChatOpenAI(api_key=settings.OPENAI_KEY,model="gpt-4o-2024-08-06")
    structuredLLM = llm.with_structured_output(factCode,strict=True)
    
    factChain = fact_prompt() | structuredLLM 
    
    # Feeding dummy fact file to agent so that it know the structure of the fact files. 
    with open(f"/var/www/html/chat-with-data/test/hotel_2023-06-08.txt", 'r') as factFile:
        factData = factFile.read()
    
    result = await factChain.ainvoke(input={'fact':factData, 'question': standaloneQuestion},config={'callbacks':callbacks,'run_name':'fact-chain'}) 
    
    if result:
        try:
            # Execute the python code writen by agent and get final data.
            data = await run_code(result.code,date)
        except Exception as e:
            print(e)
            pass
    return { 'standaloneQuestion': standaloneQuestion, 'date': date, 'type': 'factReportTool', 'data': data}