import json
from jingrow.utils.jingrow_api import get_field_mapping_from_jingrow
from jingrow.utils.jingrow_api import get_record_list

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 or {}).get("pagetype") if isinstance(config, dict) else None
        if not pagetype:
            return {"success": False, "error": "pagetype 必须指定", "condition_met": False, "should_execute": False, "flow_path": "false_path"}

        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

        label2field = get_field_mapping_from_jingrow(pagetype) or {}

        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:
                return {
                    "success": False,
                    "error": f"来源字段 {source_field} 不存在，可用字段: {list(available_fields.keys()) if available_fields else '无'}",
                    "condition_met": False,
                    "should_execute": False,
                    "flow_path": "false_path",
                    "main_output": inputs if isinstance(inputs, dict) else {},
                    "true_output": {},
                    "false_output": inputs if isinstance(inputs, dict) else {}
                }
            
            value = available_fields[source_field]
            
            target_field = field
            if field in label2field:
                target_field = label2field[field]
            else:
                for label, fieldname in label2field.items():
                    if field == label:
                        target_field = fieldname
                        break
            
            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:
                pass
        
        # 将 filters 映射为 REST 查询所需的二维数组格式
        # 兼容原先 dict/数组混合结构：等号用直接值，其它操作符为 [op, value]
        filter_array = []
        for k, v in filters.items():
            if isinstance(v, list) and len(v) >= 2:
                filter_array.append([k, v[0], v[1]])
            else:
                filter_array.append([k, "=", v])

        api_res = get_record_list(pagetype, filters=filter_array, fields=["name"], limit=1000)
        if api_res.get("success"):
            records = api_res.get("data") or []
            record_count = len(records)
            condition_met = record_count > 0
        else:
            records = []
            record_count = 0
            condition_met = False

        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:
        
        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) 