"""
变量赋值节点
"""
import logging
from typing import Any, Dict

from ..base import BaseNode, NodeContext, NodeResult
from ..registry import NodeRegistry

logger = logging.getLogger(__name__)


@NodeRegistry.register
class VariableNode(BaseNode):
    """
    变量赋值节点
    
    设置或修改变量的值
    """
    
    node_type = 'variable'
    node_name = '变量'
    node_category = 'data'
    node_icon = 'variable'
    node_description = '设置或修改变量的值'
    
    inputs = [
        {
            'name': 'value',
            'type': 'any',
            'description': '要设置的值',
        },
    ]
    
    outputs = [
        {
            'name': 'value',
            'type': 'any',
            'description': '设置后的值',
        },
    ]
    
    def execute(self, context: NodeContext) -> NodeResult:
        """执行变量赋值"""
        try:
            assignments = self.config.get('assignments', [])
            output_variables = {}
            
            for assignment in assignments:
                var_name = assignment.get('name', '')
                value_type = assignment.get('type', 'static')
                value = assignment.get('value', '')
                
                if not var_name:
                    continue
                
                # 根据类型处理值
                if value_type == 'static':
                    # 静态值
                    final_value = value
                elif value_type == 'variable':
                    # 从其他变量获取
                    final_value = context.get_variable(value, '')
                elif value_type == 'template':
                    # 模板渲染
                    final_value = context.resolve_template(value)
                elif value_type == 'json':
                    # JSON 解析
                    import json
                    final_value = json.loads(value)
                elif value_type == 'expression':
                    # 简单表达式（仅支持基本运算）
                    final_value = self._evaluate_expression(value, context)
                else:
                    final_value = value
                
                # 设置变量
                context.set_variable(var_name, final_value)
                output_variables[var_name] = final_value
            
            return NodeResult(
                success=True,
                output=output_variables,
                output_variables=output_variables,
            )
            
        except Exception as e:
            logger.exception(f'变量节点执行失败: {e}')
            return NodeResult(
                success=False,
                error=str(e),
            )
    
    def _evaluate_expression(self, expression: str, context: NodeContext) -> Any:
        """
        评估简单表达式
        
        仅支持基本的数学运算和字符串操作
        """
        # 替换变量引用
        resolved = context.resolve_template(expression)
        
        # 安全的评估环境
        safe_dict = {
            'abs': abs,
            'int': int,
            'float': float,
            'str': str,
            'len': len,
            'min': min,
            'max': max,
            'sum': sum,
            'round': round,
        }
        
        try:
            return eval(resolved, {"__builtins__": {}}, safe_dict)
        except Exception:
            return resolved
    
    @classmethod
    def get_config_schema(cls) -> Dict[str, Any]:
        """获取配置 Schema"""
        return {
            'type': 'object',
            'properties': {
                'assignments': {
                    'type': 'array',
                    'title': '变量赋值',
                    'items': {
                        'type': 'object',
                        'properties': {
                            'name': {
                                'type': 'string',
                                'title': '变量名',
                            },
                            'type': {
                                'type': 'string',
                                'title': '值类型',
                                'enum': ['static', 'variable', 'template', 'json', 'expression'],
                                'default': 'static',
                            },
                            'value': {
                                'type': 'string',
                                'title': '值',
                            },
                        },
                    },
                },
            },
        }
