#!/usr/bin/env python3
"""
查看执行日志的脚本
用于诊断数据流转问题
"""
import sys
import os
import json
from datetime import datetime

# 添加项目路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))

from app.core.database import SessionLocal
from app.models.execution import Execution
from app.models.execution_log import ExecutionLog


def format_json(data):
    """格式化JSON数据"""
    if isinstance(data, dict):
        return json.dumps(data, ensure_ascii=False, indent=2)
    return str(data)


def main():
    """主函数"""
    db = SessionLocal()
    
    try:
        # 获取最近的执行记录
        print("=" * 80)
        print("查找最近的Agent执行记录...")
        print("=" * 80)
        
        execution = db.query(Execution).filter(
            Execution.agent_id.isnot(None)
        ).order_by(Execution.created_at.desc()).first()
        
        if not execution:
            print("❌ 没有找到执行记录")
            return
        
        print(f"\n✅ 找到执行记录: {execution.id}")
        print(f"   状态: {execution.status}")
        print(f"   执行时间: {execution.execution_time}ms")
        print(f"   创建时间: {execution.created_at}")
        
        # 显示输入数据
        print("\n" + "=" * 80)
        print("输入数据 (input_data):")
        print("=" * 80)
        if execution.input_data:
            print(format_json(execution.input_data))
        else:
            print("(空)")
        
        # 显示输出数据
        print("\n" + "=" * 80)
        print("输出数据 (output_data):")
        print("=" * 80)
        if execution.output_data:
            print(format_json(execution.output_data))
        else:
            print("(空)")
        
        # 获取执行日志
        print("\n" + "=" * 80)
        print("执行日志 (按时间顺序):")
        print("=" * 80)
        
        logs = db.query(ExecutionLog).filter(
            ExecutionLog.execution_id == execution.id
        ).order_by(ExecutionLog.timestamp.asc()).all()
        
        if not logs:
            print("❌ 没有找到执行日志")
            return
        
        for i, log in enumerate(logs, 1):
            print(f"\n[{i}] {log.timestamp.strftime('%Y-%m-%d %H:%M:%S')} [{log.level}]")
            print(f"    节点: {log.node_id or '(无)'} ({log.node_type or '(无)'})")
            print(f"    消息: {log.message}")
            
            if log.data:
                print(f"    数据:")
                data_str = format_json(log.data)
                # 只显示前500个字符
                if len(data_str) > 500:
                    print(data_str[:500] + "...")
                else:
                    print(data_str)
            
            if log.duration:
                print(f"    耗时: {log.duration}ms")
        
        # 特别关注LLM节点的输入输出
        print("\n" + "=" * 80)
        print("LLM节点详细分析:")
        print("=" * 80)
        
        llm_logs = [log for log in logs if log.node_type == 'llm']
        if llm_logs:
            for log in llm_logs:
                if log.message == "节点开始执行" and log.data:
                    print(f"\n节点 {log.node_id} 的输入数据:")
                    input_data = log.data.get('input', {})
                    print(format_json(input_data))
                
                if log.message == "节点执行完成" and log.data:
                    print(f"\n节点 {log.node_id} 的输出数据:")
                    output_data = log.data.get('output', {})
                    print(format_json(output_data))
        else:
            print("❌ 没有找到LLM节点的日志")
    
    except Exception as e:
        print(f"❌ 错误: {str(e)}")
        import traceback
        traceback.print_exc()
    finally:
        db.close()


if __name__ == "__main__":
    main()
