from alayaflow.clients.alayamem.http_client import HttpAlayaMemClient


def query_vdb_message(alayamem_url: str, messages, limit, collection_name = "file_watcher_collection"):
    mem_client = HttpAlayaMemClient(alayamem_url)
    try:
        result = mem_client.vdb_query(messages, limit, collection_name)
        return {"vdb_results": result.get("results", []), "vdb_response": result}
    except Exception as e:
        return {"vdb_results": [], "error": str(e)}


def init_memory(alayamem_url: str, user_id, user_name="unknown", agent_name="unknown"):
    mem_client = HttpAlayaMemClient(alayamem_url)
    try:
        return mem_client.init_session(user_id, user_name, agent_name)
    except Exception as e:
        return {"memory_initialized": False}


def query_message(alayamem_url: str, user_id, messages):
    mem_client = HttpAlayaMemClient(alayamem_url)

    if not messages:
        return

    last_message = messages[-1]
    
    try:
        resp = mem_client.query(user_id, last_message)
    except Exception as e:
        print(f"[Query User Message] Error: {e}")
        return []

    return resp


def add_message(alayamem_url: str, user_id, session_id, messages):
    mem_client = HttpAlayaMemClient(alayamem_url)

    if not messages:
        return

    try:
        return mem_client.add_session_messages(user_id, messages)
    except Exception as e:
        print(f"[Add Messages] Error: {e}")
        pass

    return
