
import os
import json
from datetime import datetime, timedelta

from app.config.application import settings
from app.schemas.chat_schema import factCode
from app.utils.prompts import multi_fact_prompt

from langchain_openai.chat_models.base import ChatOpenAI

async def multi_fact_report(standaloneQuestion:str, fromDate:str, toDate: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")
    llm.with_structured_output(factCode,strict=True)
    factChain = multi_fact_prompt() | llm 
    
    # 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.content,fromDate, toDate)
        except Exception as e:
            print(e)
            pass
    return { 'standaloneQuestion':standaloneQuestion, 'fromDate':fromDate, 'date': toDate, 'type': 'multiFactReportTool', 'data': data}

async def run_code(code: str, fromDate: str, toDate: str):
        
    local_scope = {}
    factData = load_and_merge_json(fromDate,toDate)
    
    if not factData:
        return None
    # Pass the fact file data to the exec() in the local scope variable.
    local_scope['factData'] = factData
    
    # Execute dynamic generated code by agent.
    exec(code,globals(),local_scope)
    
    # Return the final data from the exec() local scope.
    return local_scope.get('finalData',None)

def load_and_merge_json(fromDate:str, toDate:str):
    # Convert fromDate and toDate to datetime objects
    from_date = datetime.strptime(fromDate, "%Y-%m-%d")
    to_date = datetime.strptime(toDate, "%Y-%m-%d")
    
    # Initialize an empty list to store merged JSON data
    merged_data = []

    # Iterate over the range of dates
    current_date = from_date
    while current_date <= to_date:
        # Format the current date in yyyy-mm-dd format
        date_str = current_date.strftime("%Y-%m-%d")
        
        # Build the file path
        file_path = f"/var/www/html/chat-with-data/test/hotel_{date_str}.txt"
        
        # Check if the file exists
        if os.path.exists(file_path):
            try:
                # Open and load the JSON data from the file
                with open(file_path, 'r') as factFile:
                    factData = factFile.read()
                    json_data = json.loads(factData)
                    merged_data.append(json_data)
            except Exception as e:
                print(f"Error reading {file_path}: {e}")
        
        # Move to the next date
        current_date += timedelta(days=1)

    return merged_data