"""
通用函数工具集
提供常用的图数据库操作和数据处理功能
"""

import logging

from app.core.graph.graph_operations import connect_graph
from app.core.llm.llm_service import llm_client as llm_call

logger = logging.getLogger("app")


def delete_relationships(node_id):
    """
    删除指定节点的所有关系

    Args:
        node_id: 节点ID
    """
    try:
        cql = """
        MATCH (n)-[r]-()
        WHERE id(n) = $node_id
        DELETE r
        """
        with connect_graph().session() as session:
            session.run(cql, node_id=node_id)
        return True
    except Exception as e:
        logger.error(f"删除关系错误: {e}")
        return False


def update_or_create_node(node_id, **properties):
    """
    更新或创建节点

    Args:
        node_id: 节点ID
        **properties: 节点属性

    Returns:
        节点对象
    """
    try:
        # 检查节点是否存在
        with connect_graph().session() as session:
            check_query = "MATCH (n) WHERE id(n) = $node_id RETURN n"
            result = session.run(check_query, node_id=node_id).single()

            if result:
                # 如果有属性则更新，否则只返回节点
                if properties:
                    props_string = ", ".join(
                        [f"n.{key} = ${key}" for key in properties]
                    )
                    update_query = f"""
                    MATCH (n) WHERE id(n) = $node_id
                    SET {props_string}
                    RETURN n
                    """
                    result = session.run(
                        update_query,  # type: ignore[arg-type]
                        node_id=node_id,
                        **properties,
                    ).single()
                return result["n"] if result else None
            else:
                # 节点不存在，无法更新
                logger.warning(f"节点 {node_id} 不存在，无法更新")
                return None
    except Exception as e:
        logger.error(f"更新或创建节点错误: {e}")
        return None


def get_node_by_id_no_label(node_id):
    """
    通过ID获取节点，不考虑标签

    Args:
        node_id: 节点ID

    Returns:
        节点对象
    """
    try:
        with connect_graph().session() as session:
            query = "MATCH (n) WHERE id(n) = $node_id RETURN n"
            result = session.run(query, node_id=node_id).single()
            return result["n"] if result else None
    except Exception as e:
        logger.error(f"获取节点错误: {e}")
        return None


def translate_and_parse(content):
    """
    翻译内容并返回结果

    Args:
        content: 需要翻译的内容

    Returns:
        str: 英文数据库标识符；失败时返回空字符串
    """
    translated_text = llm_call(content)
    if not translated_text:
        return ""
    return str(translated_text).strip()
