import jingrow
import json

@jingrow.whitelist()
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", {})
            branch_upstream_nodes = get_branch_upstream_nodes(current_node_id, flow_data)
            if context and "node_results" in context and branch_upstream_nodes:
                for uid in branch_upstream_nodes:
                    result = context["node_results"].get(uid)
                    if isinstance(result, dict):
                        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 = get_label_to_fieldname(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（服务端使用 jingrow.get_list）
        try:
            rows = jingrow.get_list(
                pagetype=pagetype,
                fields=["name"],
                filters=filters,
                limit_page_length=1,
            )
        except Exception as e:
            return {"success": False, "error": f"查询失败: {str(e)}", "pagetype": pagetype, "query_filters": filters}

        data = rows or []
        if not data:
            return {"success": False, "error": "未找到记录", "pagetype": pagetype, "query_filters": filters}
        first = data[0] if isinstance(data[0], dict) else None
        name = (first 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)}


def get_label_to_fieldname(pagetype: str) -> dict:
    """
    基于 PageType 元数据构建 label -> fieldname 映射，包含当前用户语言的翻译标签。
    """
    mapping = {}
    try:
        meta = jingrow.get_meta(pagetype)
        if hasattr(meta, "fields") and meta.fields:
            for df in meta.fields:
                label = str(getattr(df, "label", "") or "").strip()
                fieldname = str(getattr(df, "fieldname", "") or "").strip()
                if not fieldname:
                    continue
                if label:
                    mapping[label] = fieldname
                    try:
                        user_lang = (
                            jingrow.get_pg("User", jingrow.session.user).language
                            or jingrow.get_single("System Settings").language
                            or "zh"
                        )
                        translated_label = jingrow._(label, lang=user_lang)
                        if translated_label and translated_label != label and translated_label not in mapping:
                            mapping[translated_label] = fieldname
                    except Exception:
                        # 语言环境获取失败时忽略
                        pass
    except Exception as e:
        jingrow.log_error("获取字段映射失败", str(e))
    return mapping

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)
