import logging

from mem0llama.memory.utils import format_entities
from mem0llama.memory.models import (
    EntityExtraction,
    RelationshipExtraction,
    DeleteMemoryOutput,
    UpdateMemoryOutput,
    AddMemoryOutput,
    NoopOutput
)
from mem0llama.memory.llm_formatter import (
    parse_llm_response,
    create_entity_extraction_prompt,
    create_relationship_extraction_prompt,
    create_delete_memory_prompt,
    adapt_llm_provider_for_structured_output
)

try:
    from langchain_neo4j import Neo4jGraph
except ImportError:
    raise ImportError("langchain_community is not installed. Please install it using pip install langchain-community")

try:
    from rank_bm25 import BM25Okapi
except ImportError:
    raise ImportError("rank_bm25 is not installed. Please install it using pip install rank-bm25")

from mem0llama.graphs.tools import (
    DELETE_MEMORY_STRUCT_TOOL_GRAPH,
    DELETE_MEMORY_TOOL_GRAPH,
    EXTRACT_ENTITIES_STRUCT_TOOL,
    EXTRACT_ENTITIES_TOOL,
    RELATIONS_STRUCT_TOOL,
    RELATIONS_TOOL,
)
from mem0llama.graphs.utils import EXTRACT_RELATIONS_PROMPT, get_delete_messages
from mem0llama.utils.factory import EmbedderFactory, LlmFactory

logger = logging.getLogger(__name__)


class MemoryGraph:
    def __init__(self, config):
        self.config = config
        self.graph = Neo4jGraph(
            self.config.graph_store.config.url,
            self.config.graph_store.config.username,
            self.config.graph_store.config.password,
        )
        self.embedding_model = EmbedderFactory.create(self.config.embedder.provider, self.config.embedder.config)

        self.llm_provider = "openai_structured"
        if self.config.llm.provider:
            self.llm_provider = self.config.llm.provider
        if self.config.graph_store.llm:
            self.llm_provider = self.config.graph_store.llm.provider

        # Adapt LLM config for structured output
        llm_config = self.config.llm.config
        if self.config.graph_store.llm:
            llm_config = self.config.graph_store.llm.config
        
        self.adapted_llm_config = adapt_llm_provider_for_structured_output(
            self.llm_provider, llm_config
        )
        
        self.llm = LlmFactory.create(self.llm_provider, self.adapted_llm_config)
        self.user_id = None
        self.threshold = 0.7

    def add(self, data, filters):
        """
        Adds data to the graph.

        Args:
            data (str): The data to add to the graph.
            filters (dict): A dictionary containing filters to be applied during the addition.
        """
        entity_type_map = self._retrieve_nodes_from_data(data, filters)
        to_be_added = self._establish_nodes_relations_from_data(data, filters, entity_type_map)
        search_output = self._search_graph_db(node_list=list(entity_type_map.keys()), filters=filters)
        to_be_deleted = self._get_delete_entities_from_search_output(search_output, data, filters)

        # TODO: Batch queries with APOC plugin
        # TODO: Add more filter support
        deleted_entities = self._delete_entities(to_be_deleted, filters["user_id"])
        added_entities = self._add_entities(to_be_added, filters["user_id"], entity_type_map)

        return {"deleted_entities": deleted_entities, "added_entities": added_entities}

    def search(self, query, filters, limit=100):
        """
        Search for memories and related graph data.

        Args:
            query (str): Query to search for.
            filters (dict): A dictionary containing filters to be applied during the search.
            limit (int): The maximum number of nodes and relationships to retrieve. Defaults to 100.

        Returns:
            dict: A dictionary containing:
                - "contexts": List of search results from the base data store.
                - "entities": List of related graph data based on the query.
        """
        entity_type_map = self._retrieve_nodes_from_data(query, filters)
        search_output = self._search_graph_db(node_list=list(entity_type_map.keys()), filters=filters)

        if not search_output:
            return []

        search_outputs_sequence = [
            [item["source"], item["relationship"], item["destination"]] for item in search_output
        ]
        bm25 = BM25Okapi(search_outputs_sequence)

        tokenized_query = query.split(" ")
        reranked_results = bm25.get_top_n(tokenized_query, search_outputs_sequence, n=5)

        search_results = []
        for item in reranked_results:
            search_results.append({"source": item[0], "relationship": item[1], "destination": item[2]})

        logger.info(f"Returned {len(search_results)} search results")

        return search_results

    def delete_all(self, filters):
        cypher = """
        MATCH (n {user_id: $user_id})
        DETACH DELETE n
        """
        params = {"user_id": filters["user_id"]}
        self.graph.query(cypher, params=params)

    def get_all(self, filters, limit=100):
        """
        Retrieves all nodes and relationships from the graph database based on optional filtering criteria.

        Args:
            filters (dict): A dictionary containing filters to be applied during the retrieval.
            limit (int): The maximum number of nodes and relationships to retrieve. Defaults to 100.
        Returns:
            list: A list of dictionaries, each containing:
                - 'contexts': The base data store response for each memory.
                - 'entities': A list of strings representing the nodes and relationships
        """

        # return all nodes and relationships
        query = """
        MATCH (n {user_id: $user_id})-[r]->(m {user_id: $user_id})
        RETURN n.name AS source, type(r) AS relationship, m.name AS target
        LIMIT $limit
        """
        results = self.graph.query(query, params={"user_id": filters["user_id"], "limit": limit})

        final_results = []
        for result in results:
            final_results.append(
                {
                    "source": result["source"],
                    "relationship": result["relationship"],
                    "target": result["target"],
                }
            )

        logger.info(f"Retrieved {len(final_results)} relationships")

        return final_results

    def _retrieve_nodes_from_data(self, data, filters):
        """Extracts all the entities mentioned in the query."""
        entity_type_map = {}
        
        # Create a structured prompt for entity extraction
        prompt = create_entity_extraction_prompt(data, filters["user_id"])
        
        # Determine if we should use tools based on the LLM provider
        use_tools = self.llm_provider in ["azure_openai_structured", "openai_structured"]
        
        if use_tools:
            _tools = [EXTRACT_ENTITIES_STRUCT_TOOL]
            search_results = self.llm.generate_response(
                messages=[
                    {
                        "role": "system",
                        "content": f"You are a smart assistant who understands entities and their types in a given text. If user message contains self reference such as 'I', 'me', 'my' etc. then use {filters['user_id']} as the source entity. Extract all the entities from the text. ***DO NOT*** answer the question itself if the given text is a question.",
                    },
                    {"role": "user", "content": data},
                ],
                tools=_tools,
            )
            
            try:
                for item in search_results["tool_calls"][0]["arguments"]["entities"]:
                    entity_type_map[item["entity"]] = item["entity_type"]
            except Exception as e:
                logger.error(f"Error in search tool: {e}")
        else:
            # For local LLMs, use direct prompting with structured output
            response = self.llm.generate_response(
                messages=[
                    {"role": "system", "content": "You are an AI assistant that extracts entities and their types from text."},
                    {"role": "user", "content": prompt}
                ],
                response_format=EntityExtraction.model_json_schema()
            )
            
            # Parse the response using our Pydantic model
            try:
                # For Ollama with format parameter, the response might be directly parseable
                if isinstance(response, dict) and "message" in response and "content" in response["message"]:
                    # Direct Ollama response
                    extraction_result = EntityExtraction.model_validate_json(response["message"]["content"])
                elif isinstance(response, dict) and "content" in response:
                    # Standard response format
                    extraction_result = parse_llm_response(response["content"], EntityExtraction)
                else:
                    # Fallback to our parser
                    extraction_result = parse_llm_response(response, EntityExtraction)
                
                for entity in extraction_result.entities:
                    entity_type_map[entity.entity] = entity.entity_type
            except Exception as e:
                logger.error(f"Error parsing entity extraction response: {e}")
                logger.debug(f"Raw response: {response}")

        entity_type_map = {k.lower().replace(" ", "_"): v.lower().replace(" ", "_") for k, v in entity_type_map.items()}
        logger.debug(f"Entity type map: {entity_type_map}")
        return entity_type_map

    def _establish_nodes_relations_from_data(self, data, filters, entity_type_map):
        """Establish relations among the extracted nodes."""
        # Create a structured prompt for relationship extraction
        entity_list = list(entity_type_map.keys())
        prompt = create_relationship_extraction_prompt(data, entity_list, filters["user_id"])
        
        # Determine if we should use tools based on the LLM provider
        use_tools = self.llm_provider in ["azure_openai_structured", "openai_structured"]
        
        if use_tools:
            if self.config.graph_store.custom_prompt:
                messages = [
                    {
                        "role": "system",
                        "content": EXTRACT_RELATIONS_PROMPT.replace("USER_ID", filters["user_id"]).replace(
                            "CUSTOM_PROMPT", f"4. {self.config.graph_store.custom_prompt}"
                        ),
                    },
                    {"role": "user", "content": data},
                ]
            else:
                messages = [
                    {
                        "role": "system",
                        "content": EXTRACT_RELATIONS_PROMPT.replace("USER_ID", filters["user_id"]),
                    },
                    {"role": "user", "content": f"List of entities: {list(entity_type_map.keys())}. \n\nText: {data}"},
                ]

            _tools = [RELATIONS_STRUCT_TOOL]
            extracted_entities_response = self.llm.generate_response(
                messages=messages,
                tools=_tools,
            )

            if extracted_entities_response["tool_calls"]:
                extracted_entities = extracted_entities_response["tool_calls"][0]["arguments"]["entities"]
            else:
                extracted_entities = []
        else:
            # For local LLMs, use direct prompting with structured output
            response = self.llm.generate_response(
                messages=[
                    {"role": "system", "content": "You are an AI assistant that identifies relationships between entities."},
                    {"role": "user", "content": prompt}
                ],
                response_format=RelationshipExtraction.model_json_schema()
            )
            
            # Parse the response using our Pydantic model
            try:
                # For Ollama with format parameter, the response might be directly parseable
                if isinstance(response, dict) and "message" in response and "content" in response["message"]:
                    # Direct Ollama response
                    extraction_result = RelationshipExtraction.model_validate_json(response["message"]["content"])
                elif isinstance(response, dict) and "content" in response:
                    # Standard response format
                    extraction_result = parse_llm_response(response["content"], RelationshipExtraction)
                else:
                    # Fallback to our parser
                    extraction_result = parse_llm_response(response, RelationshipExtraction)
                
                # Convert to the format expected by the rest of the code
                extracted_entities = []
                for relationship in extraction_result.entities:
                    extracted_entities.append({
                        "source": relationship.source,
                        "relationship": relationship.relationship,
                        "destination": relationship.destination
                    })
            except Exception as e:
                logger.error(f"Error parsing relationship extraction response: {e}")
                logger.debug(f"Raw response: {response}")
                extracted_entities = []

        extracted_entities = self._remove_spaces_from_entities(extracted_entities)
        logger.debug(f"Extracted entities: {extracted_entities}")
        return extracted_entities

    def _search_graph_db(self, node_list, filters, limit=100):
        """Search similar nodes among and their respective incoming and outgoing relations."""
        result_relations = []

        for node in node_list:
            n_embedding = self.embedding_model.embed(node)

            cypher_query = """
            MATCH (n)
            WHERE n.embedding IS NOT NULL AND n.user_id = $user_id
            WITH n,
                round(reduce(dot = 0.0, i IN range(0, size(n.embedding)-1) | dot + n.embedding[i] * $n_embedding[i]) /
                (sqrt(reduce(l2 = 0.0, i IN range(0, size(n.embedding)-1) | l2 + n.embedding[i] * n.embedding[i])) *
                sqrt(reduce(l2 = 0.0, i IN range(0, size($n_embedding)-1) | l2 + $n_embedding[i] * $n_embedding[i]))), 4) AS similarity
            WHERE similarity >= $threshold
            MATCH (n)-[r]->(m)
            RETURN n.name AS source, elementId(n) AS source_id, type(r) AS relationship, elementId(r) AS relation_id, m.name AS destination, elementId(m) AS destination_id, similarity
            UNION
            MATCH (n)
            WHERE n.embedding IS NOT NULL AND n.user_id = $user_id
            WITH n,
                round(reduce(dot = 0.0, i IN range(0, size(n.embedding)-1) | dot + n.embedding[i] * $n_embedding[i]) /
                (sqrt(reduce(l2 = 0.0, i IN range(0, size(n.embedding)-1) | l2 + n.embedding[i] * n.embedding[i])) *
                sqrt(reduce(l2 = 0.0, i IN range(0, size($n_embedding)-1) | l2 + $n_embedding[i] * $n_embedding[i]))), 4) AS similarity
            WHERE similarity >= $threshold
            MATCH (m)-[r]->(n)
            RETURN m.name AS source, elementId(m) AS source_id, type(r) AS relationship, elementId(r) AS relation_id, n.name AS destination, elementId(n) AS destination_id, similarity
            ORDER BY similarity DESC
            LIMIT $limit
            """
            params = {
                "n_embedding": n_embedding,
                "threshold": self.threshold,
                "user_id": filters["user_id"],
                "limit": limit,
            }
            ans = self.graph.query(cypher_query, params=params)
            result_relations.extend(ans)

        return result_relations

    def _get_delete_entities_from_search_output(self, search_output, data, filters):
        """Get the entities to be deleted from the search output."""
        search_output_string = format_entities(search_output)
        
        # Create a structured prompt for memory deletion
        prompt = create_delete_memory_prompt(search_output_string, data, filters["user_id"])
        
        # Determine if we should use tools based on the LLM provider
        use_tools = self.llm_provider in ["azure_openai_structured", "openai_structured"]
        
        if use_tools:
            system_prompt, user_prompt = get_delete_messages(search_output_string, data, filters["user_id"])
            _tools = [DELETE_MEMORY_STRUCT_TOOL_GRAPH]
            
            memory_updates = self.llm.generate_response(
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt},
                ],
                tools=_tools,
            )
            
            to_be_deleted = []
            for item in memory_updates["tool_calls"]:
                if item["name"] == "delete_graph_memory":
                    to_be_deleted.append(item["arguments"])
        else:
            # For local LLMs, use direct prompting with structured output
            response = self.llm.generate_response(
                messages=[
                    {"role": "system", "content": "You are an AI assistant that identifies relationships to be deleted from a knowledge graph."},
                    {"role": "user", "content": prompt}
                ],
                response_format=DeleteMemoryOutput.model_json_schema()
            )
            
            # Parse the response using our Pydantic model
            try:
                # For Ollama with format parameter, the response might be directly parseable
                if isinstance(response, dict) and "message" in response and "content" in response["message"]:
                    # Direct Ollama response
                    deletion_result = DeleteMemoryOutput.model_validate_json(response["message"]["content"])
                elif isinstance(response, dict) and "content" in response:
                    # Standard response format
                    deletion_result = parse_llm_response(response["content"], DeleteMemoryOutput)
                else:
                    # Fallback to our parser
                    deletion_result = parse_llm_response(response, DeleteMemoryOutput)
                
                # Convert to the format expected by the rest of the code
                to_be_deleted = []
                for memory in deletion_result.entities:
                    to_be_deleted.append({
                        "source": memory.source,
                        "relationship": memory.relationship,
                        "destination": memory.destination
                    })
            except Exception as e:
                logger.error(f"Error parsing memory deletion response: {e}")
                logger.debug(f"Raw response: {response}")
                to_be_deleted = []
                
        # in case if it is not in the correct format
        to_be_deleted = self._remove_spaces_from_entities(to_be_deleted)
        logger.debug(f"Deleted relationships: {to_be_deleted}")
        return to_be_deleted

    def _delete_entities(self, to_be_deleted, user_id):
        """Delete the entities from the graph."""
        results = []
        for item in to_be_deleted:
            source = item["source"]
            destination = item["destination"]
            relationship = item["relationship"]

            # Delete the specific relationship between nodes
            cypher = f"""
            MATCH (n {{name: $source_name, user_id: $user_id}})
            -[r:{relationship}]->
            (m {{name: $dest_name, user_id: $user_id}})
            DELETE r
            RETURN 
                n.name AS source,
                m.name AS target,
                type(r) AS relationship
            """
            params = {
                "source_name": source,
                "dest_name": destination,
                "user_id": user_id,
            }
            result = self.graph.query(cypher, params=params)
            results.append(result)
        return results

    def _add_entities(self, to_be_added, user_id, entity_type_map):
        """Add the new entities to the graph. Merge the nodes if they already exist."""
        results = []
        for item in to_be_added:
            # entities
            source = item["source"]
            destination = item["destination"]
            relationship = item["relationship"]

            # types
            source_type = entity_type_map.get(source, "unknown")
            destination_type = entity_type_map.get(destination, "unknown")

            # embeddings
            source_embedding = self.embedding_model.embed(source)
            dest_embedding = self.embedding_model.embed(destination)

            # search for the nodes with the closest embeddings
            source_node_search_result = self._search_source_node(source_embedding, user_id, threshold=0.9)
            destination_node_search_result = self._search_destination_node(dest_embedding, user_id, threshold=0.9)

            # TODO: Create a cypher query and common params for all the cases
            if not destination_node_search_result and source_node_search_result:
                cypher = f"""
                    MATCH (source)
                    WHERE elementId(source) = $source_id
                    MERGE (destination:{destination_type} {{name: $destination_name, user_id: $user_id}})
                    ON CREATE SET
                        destination.created = timestamp(),
                        destination.embedding = $destination_embedding
                    MERGE (source)-[r:{relationship}]->(destination)
                    ON CREATE SET 
                        r.created = timestamp()
                    RETURN source.name AS source, type(r) AS relationship, destination.name AS target
                    """

                params = {
                    "source_id": source_node_search_result[0]["elementId(source_candidate)"],
                    "destination_name": destination,
                    "relationship": relationship,
                    "destination_type": destination_type,
                    "destination_embedding": dest_embedding,
                    "user_id": user_id,
                }
                resp = self.graph.query(cypher, params=params)
                results.append(resp)

            elif destination_node_search_result and not source_node_search_result:
                cypher = f"""
                    MATCH (destination)
                    WHERE elementId(destination) = $destination_id
                    MERGE (source:{source_type} {{name: $source_name, user_id: $user_id}})
                    ON CREATE SET
                        source.created = timestamp(),
                        source.embedding = $source_embedding
                    MERGE (source)-[r:{relationship}]->(destination)
                    ON CREATE SET 
                        r.created = timestamp()
                    RETURN source.name AS source, type(r) AS relationship, destination.name AS target
                    """

                params = {
                    "destination_id": destination_node_search_result[0]["elementId(destination_candidate)"],
                    "source_name": source,
                    "relationship": relationship,
                    "source_type": source_type,
                    "source_embedding": source_embedding,
                    "user_id": user_id,
                }
                resp = self.graph.query(cypher, params=params)
                results.append(resp)

            elif source_node_search_result and destination_node_search_result:
                cypher = f"""
                    MATCH (source)
                    WHERE elementId(source) = $source_id
                    MATCH (destination)
                    WHERE elementId(destination) = $destination_id
                    MERGE (source)-[r:{relationship}]->(destination)
                    ON CREATE SET 
                        r.created_at = timestamp(),
                        r.updated_at = timestamp()
                    RETURN source.name AS source, type(r) AS relationship, destination.name AS target
                    """
                params = {
                    "source_id": source_node_search_result[0]["elementId(source_candidate)"],
                    "destination_id": destination_node_search_result[0]["elementId(destination_candidate)"],
                    "user_id": user_id,
                    "relationship": relationship,
                }
                resp = self.graph.query(cypher, params=params)
                results.append(resp)

            elif not source_node_search_result and not destination_node_search_result:
                cypher = f"""
                    MERGE (n:{source_type} {{name: $source_name, user_id: $user_id}})
                    ON CREATE SET n.created = timestamp(), n.embedding = $source_embedding
                    ON MATCH SET n.embedding = $source_embedding
                    MERGE (m:{destination_type} {{name: $dest_name, user_id: $user_id}})
                    ON CREATE SET m.created = timestamp(), m.embedding = $dest_embedding
                    ON MATCH SET m.embedding = $dest_embedding
                    MERGE (n)-[rel:{relationship}]->(m)
                    ON CREATE SET rel.created = timestamp()
                    RETURN n.name AS source, type(rel) AS relationship, m.name AS target
                    """
                params = {
                    "source_name": source,
                    "source_type": source_type,
                    "dest_name": destination,
                    "destination_type": destination_type,
                    "source_embedding": source_embedding,
                    "dest_embedding": dest_embedding,
                    "user_id": user_id,
                }
                resp = self.graph.query(cypher, params=params)
                results.append(resp)
        return results

    def _remove_spaces_from_entities(self, entity_list):
        for item in entity_list:
            item["source"] = item["source"].lower().replace(" ", "_")
            item["relationship"] = item["relationship"].lower().replace(" ", "_")
            item["destination"] = item["destination"].lower().replace(" ", "_")
        return entity_list

    def _search_source_node(self, source_embedding, user_id, threshold=0.9):
        cypher = """
            MATCH (source_candidate)
            WHERE source_candidate.embedding IS NOT NULL 
            AND source_candidate.user_id = $user_id

            WITH source_candidate,
                round(
                    reduce(dot = 0.0, i IN range(0, size(source_candidate.embedding)-1) |
                        dot + source_candidate.embedding[i] * $source_embedding[i]) /
                    (sqrt(reduce(l2 = 0.0, i IN range(0, size(source_candidate.embedding)-1) |
                        l2 + source_candidate.embedding[i] * source_candidate.embedding[i])) *
                    sqrt(reduce(l2 = 0.0, i IN range(0, size($source_embedding)-1) |
                        l2 + $source_embedding[i] * $source_embedding[i])))
                , 4) AS source_similarity
            WHERE source_similarity >= $threshold

            WITH source_candidate, source_similarity
            ORDER BY source_similarity DESC
            LIMIT 1

            RETURN elementId(source_candidate)
            """

        params = {
            "source_embedding": source_embedding,
            "user_id": user_id,
            "threshold": threshold,
        }

        result = self.graph.query(cypher, params=params)
        return result

    def _search_destination_node(self, destination_embedding, user_id, threshold=0.9):
        cypher = """
            MATCH (destination_candidate)
            WHERE destination_candidate.embedding IS NOT NULL 
            AND destination_candidate.user_id = $user_id

            WITH destination_candidate,
                round(
                    reduce(dot = 0.0, i IN range(0, size(destination_candidate.embedding)-1) |
                        dot + destination_candidate.embedding[i] * $destination_embedding[i]) /
                    (sqrt(reduce(l2 = 0.0, i IN range(0, size(destination_candidate.embedding)-1) |
                        l2 + destination_candidate.embedding[i] * destination_candidate.embedding[i])) *
                    sqrt(reduce(l2 = 0.0, i IN range(0, size($destination_embedding)-1) |
                        l2 + $destination_embedding[i] * $destination_embedding[i])))
                , 4) AS destination_similarity
            WHERE destination_similarity >= $threshold

            WITH destination_candidate, destination_similarity
            ORDER BY destination_similarity DESC
            LIMIT 1

            RETURN elementId(destination_candidate)
            """
        params = {
            "destination_embedding": destination_embedding,
            "user_id": user_id,
            "threshold": threshold,
        }

        result = self.graph.query(cypher, params=params)
        return result
