#!/opt/homebrew/bin/python3.11
"""
快速状态检查
"""

import os
import sys
import time
import psutil
from datetime import datetime


def quick_check():
    print("=" * 60)
    print("快速状态检查")
    print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 60)

    # 系统负载
    load = os.getloadavg()
    cpu = psutil.cpu_percent(interval=1)
    mem = psutil.virtual_memory()

    print(f"\n📊 系统状态:")
    print(f"   负载: {load[0]:.2f} (1min), {load[1]:.2f} (5min), {load[2]:.2f} (15min)")
    print(f"   CPU: {cpu:.1f}%")
    print(
        f"   内存: {mem.percent:.1f}% ({mem.used / (1024**3):.1f}GB / {mem.total / (1024**3):.1f}GB)"
    )

    # 检查处理器进程
    print(f"\n🔍 处理器进程:")

    processor_counts = {}
    high_cpu_processes = []

    for proc in psutil.process_iter(["pid", "name", "cmdline", "cpu_percent"]):
        try:
            cmdline = " ".join(proc.info["cmdline"]) if proc.info["cmdline"] else ""
            cpu = proc.info.get("cpu_percent", 0)

            # 检查各种处理器
            if "asr_processor" in cmdline:
                processor_counts["asr"] = processor_counts.get("asr", 0) + 1
                if cpu > 50:
                    high_cpu_processes.append(f"ASR PID {proc.pid}: {cpu:.1f}%")
            elif "cut_processor" in cmdline:
                processor_counts["cut"] = processor_counts.get("cut", 0) + 1
                if cpu > 50:
                    high_cpu_processes.append(f"CUT PID {proc.pid}: {cpu:.1f}%")
            elif "ocr_processor" in cmdline:
                processor_counts["ocr"] = processor_counts.get("ocr", 0) + 1
            elif "yolo_processor" in cmdline:
                processor_counts["yolo"] = processor_counts.get("yolo", 0) + 1
            elif "face_processor" in cmdline:
                processor_counts["face"] = processor_counts.get("face", 0) + 1
            elif "pose_processor" in cmdline:
                processor_counts["pose"] = processor_counts.get("pose", 0) + 1

        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue

    # 显示处理器计数
    for proc_type, count in processor_counts.items():
        print(f"   {proc_type.upper()}: {count} 个进程")

    # 显示高CPU进程
    if high_cpu_processes:
        print(f"\n⚠️  高CPU进程:")
        for proc_info in high_cpu_processes[:5]:  # 只显示前5个
            print(f"   {proc_info}")
        if len(high_cpu_processes) > 5:
            print(f"   ... 还有 {len(high_cpu_processes) - 5} 个高CPU进程")

    # 检查输出目录
    output_dir = "/Users/accusys/momentry/output"
    if os.path.exists(output_dir):
        asr_files = len(
            [f for f in os.listdir(output_dir) if "_asr_" in f and f.endswith(".json")]
        )
        cut_files = len(
            [f for f in os.listdir(output_dir) if "_cut_" in f and f.endswith(".json")]
        )

        print(f"\n📁 输出文件:")
        print(f"   ASR文件: {asr_files} 个")
        print(f"   CUT文件: {cut_files} 个")

    # 状态总结
    print(f"\n📈 状态总结:")

    if load[0] > 8:
        print(f"   ⚠️  系统负载很高 ({load[0]:.2f})")
        if processor_counts.get("asr", 0) > 0 or processor_counts.get("cut", 0) > 0:
            print(f"     可能原因: ASR/CUT 视频处理中")
    elif load[0] > 4:
        print(f"   ℹ️  系统负载中等 ({load[0]:.2f})")
    else:
        print(f"   ✅ 系统负载正常 ({load[0]:.2f})")

    if mem.percent > 90:
        print(f"   ⚠️  内存使用率很高 ({mem.percent:.1f}%)")
    elif mem.percent > 80:
        print(f"   ℹ️  内存使用率较高 ({mem.percent:.1f}%)")
    else:
        print(f"   ✅ 内存使用率正常 ({mem.percent:.1f}%)")

    # 建议
    print(f"\n💡 建议:")
    if processor_counts.get("asr", 0) > 0 or processor_counts.get("cut", 0) > 0:
        print(f"   1. ASR/CUT 处理进行中，建议等待完成")
        print(f"   2. 处理完成后系统负载会恢复正常")
    else:
        print(f"   1. 没有运行中的处理器，可以继续下一步工作")

    print(f"\n⏱️  检查完成")
    print("=" * 60)


if __name__ == "__main__":
    try:
        quick_check()
    except KeyboardInterrupt:
        print(f"\n检查被中断")
        sys.exit(0)
    except Exception as e:
        print(f"\n错误: {e}")
        sys.exit(1)
