import sys
import os
import json

import jingrow

def execute(context=None, inputs=None, config=None, **kwargs):
    """
    获取指定记录的 name 值（简化版）
    - 仅支持 filter_conditions（对象数组）
    - 将中文/标签字段名映射为真实字段名
    - 从同一分支上游节点获取可用字段值
    """
    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") or (inputs.get("pagetype") if isinstance(inputs, dict) else None)
        if not pagetype:
            return {"success": False, "error": "pagetype 必填"}

        filter_conditions = (config or {}).get("filter_conditions") or (inputs.get("filter_conditions") if isinstance(inputs, dict) else None)
        if not filter_conditions:
            return {"success": False, "error": "filter_conditions 必填"}

        # 收集可用字段：inputs + 同一分支上游节点
        available_fields = {}
        if isinstance(inputs, dict):
            available_fields.update(inputs)

        try:
            current_node_id = context.get("current_node_id")
            flow_data = context.get("flow_data", {})
            if context and "node_results" in context and current_node_id and flow_data:
                edges = flow_data.get("edges", [])
                upstream_nodes = set()
                stack = [current_node_id]
                while stack:
                    nid = stack.pop()
                    for e in edges:
                        if e.get("target") == nid:
                            sid = e.get("source")
                            if sid and sid not in upstream_nodes:
                                upstream_nodes.add(sid)
                                stack.append(sid)
                for uid in upstream_nodes:
                    result = context["node_results"].get(uid)
                    if isinstance(result, dict):
                        # 解析 AI 原始响应中的 JSON
                        if isinstance(result.get("ai_raw_response"), str):
                            try:
                                raw = result["ai_raw_response"].strip()
                                lb, rb = raw.find('{'), raw.rfind('}')
                                if lb != -1 and rb != -1 and rb > lb:
                                    obj = json.loads(raw[lb:rb+1])
                                    if isinstance(obj, dict):
                                        for k, v in obj.items():
                                            if k not in available_fields or not available_fields.get(k):
                                                available_fields[k] = v
                            except Exception:
                                pass
                        # 平铺其它键
                        for k, v in result.items():
                            if k not in available_fields or not available_fields.get(k):
                                available_fields[k] = v
        except Exception:
            pass

        # 构造查询条件
        try:
            label2field = jingrow.get_field_mapping_from_jingrow(pagetype) or {}
            filters = []
            for cond in filter_conditions or []:
                if not isinstance(cond, dict):
                    continue
                field_label = cond.get("field")
                operator = cond.get("operator")
                source_field = cond.get("source_field")
                if not all([field_label, operator, source_field]):
                    continue
                
                # 从可用字段取值
                value = available_fields.get(source_field)
                if value is None:
                    return {"success": False, "error": f"来源字段 {source_field} 不存在，可用字段: {list(available_fields.keys())}"}
                
                # 将标签字段映射为真实字段名
                target_field = label2field.get(str(field_label).strip(), field_label)
                
                if operator == "=":
                    filters.append([target_field, "=", value])
                elif operator == "!=":
                    filters.append([target_field, "!=", value])
                elif operator == "in":
                    if isinstance(value, list):
                        filters.append([target_field, "in", value])
                    else:
                        filters.append([target_field, "in", [value]])
                elif operator == "like":
                    filters.append([target_field, "like", f"%{value}%"]) 
                else:
                    # 其它操作符直接透传
                    filters.append([target_field, operator, value])
            
            if not filters:
                return {"success": False, "error": "没有有效的过滤条件"}
                
        except Exception as e:
            return {"success": False, "error": f"构造查询条件失败: {str(e)}"}

        # 查询第一条记录 name
        records = jingrow.get_list(pagetype, filters=filters, fields=["name"], limit=1)
        if not records:
            return {"success": False, "error": "未找到记录", "pagetype": pagetype, "query_filters": filters}
        name = (records[0] or {}).get("name")
        if not name:
            return {"success": False, "error": "记录缺少name字段", "pagetype": pagetype, "query_filters": filters}

        # 添加调试信息
        print(f"get_record_name 查询成功: pagetype={pagetype}, filters={filters}, found_name={name}")
        
        return {"success": True, "record_name": name, "pagetype": pagetype, "query_filters": filters}

    except Exception as e:
        return {"success": False, "error": str(e)}