import json

from alayaflow.api import Flow

def main():
    # Initialize flow api singleton

    flow = Flow()
    flow.init({
        "alayahub_url": "http://xxxx",
    })

    workflow_id = 'autotable'
    workflow_version = '1.0.0'
    init_args = {
        "alayamem_url": "http://10.16.70.46:5555",
    }
    flow.load_workflow(workflow_id, workflow_version, init_args)

    # 新的输入格式：使用 fields 字段，支持递归结构
    input_data = {
        "fields": [
            "工作单位",
            {"个人信息": ["姓名", {"联系方式": ["电话", "邮箱"]}]},
            "主要学习工作经历"
        ],
        "tasks": [],
        "context_by_task": {},
        "final_result": {},
        "errors": {},
    }
    user_config = {
        "collection_name": "file_watcher_collection",
    }
        
    final_result = None
    for event in flow.exec_workflow(workflow_id, workflow_version, input_data, user_config):
        if "error" in event:
            print(f"\n[Error] {event['error']}")
            break
        # 查找包含最终状态的事件
        # LangGraph 的 astream_events 可能在 data.output 或 data 中包含最终状态
        if "data" in event:
            data = event["data"]
            # 检查 output 字段（通常是最终状态）
            if isinstance(data, dict) and "output" in data:
                output = data["output"]
                if isinstance(output, dict) and ("context_by_task" in output or "final_result" in output):
                    final_result = output
            # 或者直接检查 data 中是否包含最终状态字段
            elif isinstance(data, dict) and ("context_by_task" in data or "final_result" in data):
                final_result = data
    
    # 打印最终结果
    if final_result:
        print("\n最终结果：")
        print(json.dumps(final_result.get("final_result", {}), indent=2, ensure_ascii=False))

if __name__ == '__main__':
    main()