import json
from typing import Dict, Any, Optional

from jingrow.utils.jingrow_api import (
    get_field_mapping_from_jingrow,
    create_record,
    map_fields_by_labels,
)

def execute(context=None, inputs=None, config=None):
    """
    创建记录节点 - 适配自 jingrow 系统
    根据输入数据创建新的记录
    """
    try:
        # 参数处理
        if context is None:
            context = {}
        if inputs is None:
            inputs = {}
        if config is None:
            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:
            return {
                "success": False,
                "error": "pagetype 必须为非空字符串，请检查配置"
            }

        field_map = config.get("field_map", [])
        
        # 从 Jingrow 获取字段 label->fieldname 映射
        label2field = get_field_mapping_from_jingrow(record_type) or {}
        
        # 收集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
        
        # 目标记录数据
        record_data = {}
        mapped_fields = set()
        
        # 1. 优先用field_map（from→to）
        if field_map:
            record_data.update(map_fields_by_labels(field_map, ai_outputs, label2field))
            mapped_fields.update([m.get("from") for m in field_map if m.get("from")])
            # 同时标记目标字段为已映射，防止被自动映射覆盖
            for mapping in field_map:
                to_field = mapping.get("to")
                if to_field:
                    # 将目标字段名也标记为已映射
                    mapped_fields.add(to_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 is not None and fieldname not in record_data:
                record_data[fieldname] = value
                mapped_fields.add(label)
        
        # 调用 Jingrow 创建记录
        api_res = create_record(record_type, record_data)
        if not api_res.get("success"):
            return {"success": False, "error": api_res.get("error", "创建记录失败")}

        created = api_res.get("data", {})
        created_name = created.get("name") or record_data.get("name")
        created_id = created.get("name") or created.get("id")  # 兼容不同返回

        return {
            "success": True,
            "created_record": {
                "name": created_name,
                "pagetype": record_type
            }
        }
        
    except Exception as e:
        # 构建详细的错误信息
        error_details = {
            "error": str(e),
            "record_type": record_type if 'record_type' in locals() else None,
            "inputs": ai_outputs if 'ai_outputs' in locals() else inputs,
            "field_map": field_map if 'field_map' in locals() else [],
            "mapped_fields": list(mapped_fields) if 'mapped_fields' in locals() else []
        }
        
        print(f"CreateRecord异常: {json.dumps(error_details, ensure_ascii=False, indent=2)}")
        
        return {
            "success": False,
            "error": str(e),
            "error_details": error_details
        }

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)
