import subprocess
import json
import os

def run_command_and_extract_numbers(command, filepath):
    """运行命令并从结果中提取数字，并返回数字列表。"""
    try:
        command = f"cat {filepath} | {command}"
        result = subprocess.run(command, shell=True, text=True, capture_output=True)
        numbers = [float(number) for line in result.stdout.splitlines() for number in line.split()]
        return numbers
    except Exception as e:
        print(f"Error running command: {e}")
        return []

def save_numbers_to_combined_json(log_files, commands, output_file):
    """从日志文件中提取数字，并保存到合并后的JSON文件。"""
    combined_data = {}
    
    for log_file, command in zip(log_files, commands):
        try:
            log_numbers = run_command_and_extract_numbers(command, log_file)
            key = os.path.basename(log_file).split('.')[0]
            combined_data[key] = log_numbers
        except Exception as e:
            print(f"Error processing {log_file}: {e}")
    
    with open(output_file, 'w') as file:
        json.dump(combined_data, file)
    print(f"Saved combined data to {output_file}")

def main():
    analysis_config = {
        "check_list": [
            {"file": "/root/presurelog/test_cpu.log", "cmd": "grep 'total number of events' | awk -F: '{print $2}'"},
            {"file": "/root/presurelog/test_gpu.log", "cmd": "grep -v test"},
            {"file": "/root/presurelog/test_mlc_latency_matrix.log", "cmd": "tail -n 2 | awk '{print $2, $3}'"},
            {"file": "/root/presurelog/test_mlc_max_bandwidth.log", "cmd": "tail -n 5 | awk '{print $NF}'"},
            {"file": "/root/presurelog/test_pcie_p2p.log", "cmd": "tail -n 4 | head -n 1 | awk '{print $2, $3, $4, $5, $6, $7, $8}'"}
        ],
        "output_file": '/root/presurelog/combined_numbers.json'
    }

    log_files = [config['file'] for config in analysis_config['check_list']]
    commands = [config['cmd'] for config in analysis_config['check_list']]
    output_file = analysis_config['output_file']

    save_numbers_to_combined_json(log_files, commands, output_file)

if __name__ == "__main__":
    main()
