from datetime import datetime, timedelta

import requests

URL_SHORTTERM_GET_RUNIDS = "http://127.0.0.1:19527/shortterm_get_runids"
URL_SHORTTERM_GET = "http://127.0.0.1:19527/shortterm_get"
URL_SHORTTERM_DELETE = "http://127.0.0.1:19527/shortterm_delete"
URL_LONGTERM_ADD = "http://127.0.0.1:19527/longterm_add"


def get_runids(comparison_time):
    data = {"timestamp": comparison_time.isoformat()}
    try:
        response = requests.post(URL_SHORTTERM_GET_RUNIDS, json=data)

        if response.status_code == 200:
            return response.json()["data"]
        else:
            print("Failed with status code:", response.status_code)
            return []
    except Exception as e:
        print(f"An error occurred: {e}")
        return []


def get_memory(run_id, comparison_time):
    data = {"run_id": run_id, "timestamp": comparison_time.isoformat()}
    try:
        response = requests.post(URL_SHORTTERM_GET, json=data)
        if response.status_code == 200:
            return response.json()["data"]
        else:
            print("Failed with status code:", response.status_code)
            return []
    except Exception as e:
        print(f"An error occurred: {e}")
        return []


def add_longterm(run_id, conversation):
    try:
        messages = []
        user_id = ""
        agent_id = ""
        for item in conversation:
            role = "user"
            text = item["content"]["text"]
            if item["user_id"] == item["agent_id"]:
                role = "assistant"
                agent_id = item["agent_id"]
            else:
                role = "user"
                user_id = item["user_id"]
            messages.append({"role": role, "content": text})
        data = {"messages": messages, "user_id": user_id, "agent_id": agent_id, "run_id": run_id}
        response = requests.post(URL_LONGTERM_ADD, json=data)
        if response.status_code == 200:
            return True
        else:
            print("Failed with status code:", response.status_code)
            return False
    except Exception as e:
        print(f"An error occurred: {e}")
        return False


def delete_shortterm(id):
    data = {"id": id}
    try:
        response = requests.post(URL_SHORTTERM_DELETE, json=data)
        if response.status_code == 200:
            return
        else:
            print("Failed with status code:", response.status_code)
            return
    except Exception as e:
        print(f"An error occurred: {e}")
        return


def main():
    comparison_time = datetime.now() - timedelta(hours=0)
    runids = get_runids(comparison_time)
    for item1 in runids:
        conversation = get_memory(item1["run_id"], comparison_time)
        print(conversation)
        if add_longterm(item1["run_id"], conversation):
            for item2 in conversation:
                delete_shortterm(item2["id"])


if __name__ == "__main__":
    main()
