#!/usr/bin/env python3
"""
查看Switch节点日志的专用脚本
用于诊断Switch节点的分支过滤问题
"""
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("Switch节点相关日志:")
        print("=" * 80)
        
        logs = db.query(ExecutionLog).filter(
            ExecutionLog.execution_id == execution.id
        ).order_by(ExecutionLog.timestamp.asc()).all()
        
        if not logs:
            print("❌ 没有找到执行日志")
            return
        
        # 筛选Switch节点相关的日志
        switch_logs = []
        for log in logs:
            if log.node_type == 'switch' or 'Switch' in log.message or '[rjb] Switch' in log.message:
                switch_logs.append(log)
        
        if not switch_logs:
            print("❌ 没有找到Switch节点相关的日志")
            print("\n所有日志节点类型:")
            node_types = set(log.node_type for log in logs if log.node_type)
            for nt in sorted(node_types):
                print(f"  - {nt}")
            return
        
        print(f"\n找到 {len(switch_logs)} 条Switch节点相关日志:\n")
        
        for i, log in enumerate(switch_logs, 1):
            print(f"[{i}] {log.timestamp.strftime('%H:%M:%S.%f')[:-3]} [{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)
                # 显示完整数据
                for line in data_str.split('\n'):
                    print(f"      {line}")
            
            if log.duration:
                print(f"    耗时: {log.duration}ms")
            print()
        
        # 特别分析Switch节点的匹配和过滤过程
        print("=" * 80)
        print("Switch节点执行流程分析:")
        print("=" * 80)
        
        match_logs = [log for log in switch_logs if '匹配' in log.message]
        filter_logs = [log for log in switch_logs if '过滤' in log.message]
        
        if match_logs:
            print("\n📊 匹配阶段:")
            for log in match_logs:
                if log.data:
                    data = log.data
                    print(f"  节点 {log.node_id}:")
                    print(f"    字段: {data.get('field', 'N/A')}")
                    print(f"    字段值: {data.get('field_value', 'N/A')}")
                    print(f"    匹配的分支: {data.get('matched_case', 'N/A')}")
                    print(f"    处理后的输入键: {data.get('processed_input_keys', 'N/A')}")
        
        if filter_logs:
            print("\n🔍 过滤阶段:")
            for log in filter_logs:
                if log.data:
                    data = log.data
                    print(f"  节点 {log.node_id}:")
                    print(f"    匹配的分支: {data.get('branch', 'N/A')}")
                    print(f"    过滤前边数: {data.get('edges_before', 'N/A')}")
                    print(f"    保留边数: {data.get('edges_kept', 'N/A')}")
                    print(f"    移除边数: {data.get('edges_removed', 'N/A')}")
        
        # 检查意图理解节点的输出
        print("\n" + "=" * 80)
        print("意图理解节点输出分析:")
        print("=" * 80)
        
        intent_logs = [log for log in logs if log.node_id and 'intent' in log.node_id.lower()]
        if intent_logs:
            for log in intent_logs:
                if log.message == "节点执行完成" and log.data:
                    print(f"\n节点 {log.node_id} 的输出:")
                    output = log.data.get('output', {})
                    print(format_json(output))
        else:
            print("❌ 没有找到意图理解节点的日志")
        
        # 检查所有节点的输出（用于调试）
        print("\n" + "=" * 80)
        print("所有节点输出摘要:")
        print("=" * 80)
        
        node_outputs = {}
        for log in logs:
            if log.message == "节点执行完成" and log.node_id:
                node_outputs[log.node_id] = log.data.get('output', {})
        
        for node_id, output in node_outputs.items():
            if isinstance(output, str) and len(output) > 100:
                print(f"{node_id}: {output[:100]}...")
            else:
                print(f"{node_id}: {output}")
    
    except Exception as e:
        print(f"❌ 错误: {str(e)}")
        import traceback
        traceback.print_exc()
    finally:
        db.close()


if __name__ == "__main__":
    main()
