import jingrow
import json
import re

@jingrow.whitelist()
def execute(context=None, inputs=None, config=None, **kwargs):
    if context is None:
        context = kwargs.get("context", {})
    if inputs is None:
        inputs = kwargs.get("inputs", {})
    if config is None:
        config = kwargs.get("config", {})

    # 获取 pagetype，兼容两层结构
    record_type = None
    if isinstance(inputs, dict):
        record_type = inputs.get("pagetype")
    if not record_type and isinstance(config, dict):
        record_type = config.get("pagetype")
    if not record_type and isinstance(config, dict) and isinstance(config.get("config"), dict):
        record_type = config["config"].get("pagetype")
    if not isinstance(record_type, str) or not record_type:
        jingrow.throw("参数错误", "pagetype 必须为非空字符串，请检查配置")

    field_map = config.get("field_map", [])
    try:
        # 获取目标pagetype的meta，建立label到fieldname映射
        meta = jingrow.get_meta(record_type)
        label2field = {}
        if hasattr(meta, 'fields'):
            for f in meta.fields:
                if hasattr(f, 'label') and hasattr(f, 'fieldname'):
                    label2field[str(f.label).strip()] = str(f.fieldname).strip()
        
        # 创建新记录
        record = jingrow.new_pg(record_type)
        mapped_fields = set()
        
        # 收集AI输出：只平铺同一分支的所有上游节点数据
        ai_outputs = {}
        if isinstance(inputs, dict):
            ai_outputs.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):
                                        ai_outputs.update(parsed_json)
                            except:
                                continue
                        
                        # 平铺其他字段到ai_outputs
                        for k, v in upstream_result.items():
                            if k not in ai_outputs or not ai_outputs.get(k):
                                ai_outputs[k] = v
        
        # 1. 优先用field_map（from→to）
        for mapping in field_map:
            from_field = mapping.get("from")
            to_field = mapping.get("to")
            value = ai_outputs.get(from_field)
            if value is not None:
                # 目标字段支持输入字段Label，如果是Label则转换为fieldname
                target_field = to_field
                if to_field in label2field:
                    target_field = label2field[to_field]
                else:
                    # 支持多语言Label匹配
                    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"
                            # 将字段Label翻译到用户语言
                            translated_label = jingrow._(label, lang=user_lang)
                            if to_field == translated_label:
                                target_field = fieldname
                                break
                        except:
                            continue
                
                record.set(target_field, value)
                mapped_fields.add(from_field)
        
        # 同步将目标字段名也标记为已映射，防止自动映射覆盖
        # 注：如果上面未添加，补充为兼容性处理（不会重复添加）
        for mapping in field_map:
            to_field = mapping.get("to")
            if to_field:
                # 如果是 Label，转换后再标记
                target_field = label2field.get(str(to_field).strip(), str(to_field).strip())
                mapped_fields.add(target_field)

        # 2. 自动标签映射：即使存在 field_map 也进行补充映射（支持多语言翻译）
        for label, value in ai_outputs.items():
            if label in mapped_fields:
                continue
            
            # 尝试直接匹配
            fieldname = label2field.get(str(label).strip())
            if fieldname and fieldname not in mapped_fields:
                record.set(fieldname, value)
                mapped_fields.add(label)
                mapped_fields.add(fieldname)
                continue
            
            # 尝试多语言翻译匹配
            input_label = str(label).strip()
            for available_label in label2field.keys():
                available_label_str = str(available_label).strip()
                try:
                    translation_lang = jingrow.get_pg("User", jingrow.session.user).language or jingrow.get_single("System Settings").language or "en"
                    translated_label = jingrow._(available_label_str, lang=translation_lang)
                    if input_label == translated_label:
                        fieldname = label2field[available_label]
                        if fieldname not in mapped_fields:
                            record.set(fieldname, value)
                            mapped_fields.add(label)
                            mapped_fields.add(fieldname)
                        break
                except:
                    continue                 
        # 保存记录
        record.save(ignore_permissions=True)
        jingrow.db.commit()
        
        return {
            "success": True,
            "created_record": {
                "name": record.name,
                "pagetype": record_type
            }
        }
    except Exception as e:
        # 构建详细的错误信息，包含上游节点输出
        error_details = {
            "error": str(e),
            "record_type": record_type,
            "inputs": ai_outputs,
            "field_map": field_map,
            "label2field": label2field,
            "mapped_fields": list(mapped_fields) if 'mapped_fields' in locals() else [],
            "branch_upstream_nodes": branch_upstream_nodes if 'branch_upstream_nodes' in locals() else []
        }
        
        jingrow.log_error(
            "CreateRecord异常", 
            f"错误详情: {json.dumps(error_details, ensure_ascii=False, indent=2)}"
        )
        
        return {
            "success": False,
            "error": str(e)
        }

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) 