#!/usr/bin/env python3
"""
检查 tmux 会话状态的脚本
"""

import subprocess
import sys
import time

def capture_session_output(session_name):
    """捕获 tmux 会话的输出"""
    try:
        # 捕获会话的当前输出
        cmd = f"tmux capture-pane -t {session_name} -p"
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        
        if result.returncode == 0:
            return True, result.stdout
        else:
            return False, result.stderr
            
    except Exception as e:
        return False, str(e)

def send_command_and_capture(session_name, command, wait_time=2):
    """发送命令并捕获输出"""
    try:
        # 发送命令
        send_cmd = f"tmux send-keys -t {session_name} '{command}' Enter"
        subprocess.run(send_cmd, shell=True, capture_output=True)
        
        # 等待命令执行
        time.sleep(wait_time)
        
        # 捕获输出
        success, output = capture_session_output(session_name)
        return success, output
        
    except Exception as e:
        return False, str(e)

def main():
    if len(sys.argv) != 2:
        print("使用方法: python3 check_session_status.py <会话名称>")
        sys.exit(1)
    
    session_name = sys.argv[1]
    
    print(f"🔍 检查会话: {session_name}")
    
    # 检查会话是否存在
    try:
        result = subprocess.run(f"tmux has-session -t {session_name}", 
                              shell=True, capture_output=True)
        if result.returncode != 0:
            print(f"❌ 会话 {session_name} 不存在")
            sys.exit(1)
    except Exception as e:
        print(f"❌ 检查会话失败: {e}")
        sys.exit(1)
    
    print(f"✅ 会话 {session_name} 存在")
    
    # 获取当前输出
    print("\n📄 当前会话输出:")
    print("-" * 50)
    success, output = capture_session_output(session_name)
    if success:
        print(output)
    else:
        print(f"❌ 无法捕获输出: {output}")
    print("-" * 50)
    
    # 发送测试命令
    test_commands = [
        ("pwd", "检查当前目录"),
        ("whoami", "检查当前用户"),
        ("hostname", "检查主机名"),
        ("docker ps 2>/dev/null || echo 'Docker 不可用'", "检查 Docker")
    ]
    
    for cmd, desc in test_commands:
        print(f"\n🔍 {desc}: {cmd}")
        success, output = send_command_and_capture(session_name, cmd)
        if success:
            # 只显示最后几行输出
            lines = output.strip().split('\n')
            relevant_lines = [line for line in lines[-10:] if line.strip()]
            if relevant_lines:
                print("输出:")
                for line in relevant_lines[-3:]:  # 只显示最后3行
                    print(f"  {line}")
        else:
            print(f"❌ 命令执行失败: {output}")

if __name__ == "__main__":
    main() 