import jingrow
import json

@jingrow.whitelist()
def execute(context=None, inputs=None, config=None, **kwargs):
    """条件判断节点：检查指定pagetype的记录是否满足条件"""
    if context is None:
        context = kwargs.get("context", {})
    if inputs is None:
        inputs = kwargs.get("inputs", {})
    if config is None:
        config = kwargs.get("config", {})

    try:
        pagetype = config.get("pagetype")
        if not pagetype:
            jingrow.throw("参数错误", "pagetype 必须指定")

        filter_conditions = config.get("filter_conditions", [])

        available_fields = {}
        if isinstance(inputs, dict):
            available_fields.update(inputs)
        
        # 获取同一分支的所有上游节点数据
        current_node_id = context.get("current_node_id")
        flow_data = context.get("flow_data", {})
        branch_upstream_nodes = get_branch_upstream_nodes(current_node_id, flow_data)
        
        if context and "node_results" in context and branch_upstream_nodes:
            node_results = context["node_results"]
            for upstream_node_id in branch_upstream_nodes:
                if upstream_node_id in node_results:
                    upstream_result = node_results[upstream_node_id]
                    if isinstance(upstream_result, dict):
                        # 如果有ai_raw_response，尝试解析JSON内容
                        if "ai_raw_response" in upstream_result and isinstance(upstream_result["ai_raw_response"], str):
                            try:
                                raw_response = upstream_result["ai_raw_response"].strip()
                                start_brace = raw_response.find('{')
                                end_brace = raw_response.rfind('}')
                                
                                if start_brace != -1 and end_brace != -1 and end_brace > start_brace:
                                    json_content = raw_response[start_brace:end_brace + 1]
                                    parsed_json = json.loads(json_content)
                                    if isinstance(parsed_json, dict):
                                        available_fields.update(parsed_json)
                            except:
                                continue
                        
                        # 平铺其他字段到available_fields
                        for k, v in upstream_result.items():
                            if k not in available_fields or not available_fields.get(k):
                                available_fields[k] = v

        meta = jingrow.get_meta(pagetype)
        label2field = {}
        for df in meta.get("fields", []):
            if df.get("label"):
                label2field[df.get("label")] = df.get("fieldname")

        filters = {}
        
        for condition in filter_conditions:
            if not isinstance(condition, dict):
                continue
                
            field = condition.get("field")
            operator = condition.get("operator")
            source_field = condition.get("source_field")
            
            if not all([field, operator, source_field]):
                continue
            
            if source_field not in available_fields:
                jingrow.throw("配置错误", f"来源字段 {source_field} 不存在，可用字段: {list(available_fields.keys()) if available_fields else '无'}")
            
            value = available_fields[source_field]
            
            target_field = field
            if field in label2field:
                target_field = label2field[field]
            else:
                for label, fieldname in label2field.items():
                    try:
                        user_lang = jingrow.get_pg("User", jingrow.session.user).language or jingrow.get_single("System Settings").language or "en"
                        translated_label = jingrow._(label, lang=user_lang)
                        if field == translated_label:
                            target_field = fieldname
                            break
                    except:
                        continue
            
            if operator == "=":
                filters[target_field] = value
            elif operator == "!=":
                filters[target_field] = ["!=", value]
            elif operator == "in":
                if isinstance(value, list):
                    filters[target_field] = ["in", value]
                else:
                    filters[target_field] = ["in", [value]]
            elif operator == "like":
                filters[target_field] = ["like", f"%{value}%"]
            else:
                jingrow.log_error("不支持的操作符", f"操作符 {operator} 不支持")
        
        try:
            records = jingrow.get_list(pagetype, filters=filters, fields=["name"], limit_page_length=None)
            record_count = len(records) if records else 0
            condition_met = record_count > 0
            
        except Exception as query_error:
            jingrow.log_error(
                "ConditionCheck查询异常",
                f"查询pagetype {pagetype}时发生错误: {str(query_error)}"
            )
            condition_met = False
            record_count = 0

        result = {
            "success": True,
            "condition_met": condition_met,
            "record_count": record_count,
            "should_execute": True,
            "pagetype": pagetype,
            "filter_conditions": filter_conditions,
            "query_filters": filters,
            "flow_path": "true_path" if condition_met else "false_path",
            "main_output": available_fields,
            "true_output": available_fields if condition_met else {},
            "false_output": available_fields if not condition_met else {}
        }

        return result

    except Exception as e:
        jingrow.log_error("ConditionCheck异常", str(e))
        
        return {
            "success": False,
            "error": str(e),
            "condition_met": False,
            "should_execute": False,
            "flow_path": "false_path",
            "main_output": inputs if inputs else {},
            "true_output": {},
            "false_output": inputs if inputs else {}
        }

def get_branch_upstream_nodes(current_node_id, flow_data):
    """获取同一分支的所有上游节点ID列表"""
    if not current_node_id or not flow_data:
        return []
    
    edges = flow_data.get("edges", [])
    upstream_nodes = set()
    stack = [current_node_id]
    
    while stack:
        node_id = stack.pop()
        for edge in edges:
            if edge.get("target") == node_id:
                source_id = edge.get("source")
                if source_id and source_id not in upstream_nodes:
                    upstream_nodes.add(source_id)
                    stack.append(source_id)
    
    return list(upstream_nodes) 