#!/usr/bin/env python3
import sys
import json
import argparse
import glob

class Colors:
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    BOLD = '\033[1m'
    END = '\033[0m'

def get_throttling_count():
    """Получение общего количества тротлинга по всем ядрам"""
    total = 0
    throttle_files = glob.glob('/sys/devices/system/cpu/cpu*/thermal_throttle/*throttle*count')
    
    if not throttle_files:
        # Альтернативный поиск
        throttle_files = glob.glob('/sys/devices/system/cpu/intel_thermal/*throttle*count')
    
    for file in throttle_files:
        try:
            with open(file, 'r') as f:
                total += int(f.read().strip())
        except:
            # print(f"Ошибка: Не удалось открыть файл {file}")
            continue
    
    return total if total > 0 else 0

def get_color(count, limit=100):
    """Получение цвета для кол-ва vcpu"""
    if count < limit/2:
        return Colors.GREEN
    elif count < limit:
        return Colors.YELLOW
    else:
        return Colors.RED + Colors.BOLD

def main():
	parser = argparse.ArgumentParser()
	parser.add_argument('--json', action='store_true', help='Вывод в формате JSON')
	parser.add_argument('--nocolor', action='store_true', help='Вывод без цветовых акцентов')
	args = parser.parse_args()

	ref = 100
	title = f"Тротлинг cpu (не более {ref})"	
	count = get_throttling_count()
	
	if count is None:
		print("Ошибка: Не удалось получить информацию о тротлинге")
		sys.exit(1)

	if args.json:
		result = [{
			"title": title,
			"value": count,
			"reference": ref,
			"format": "{x:.0f}",
			"condition": "less"
		}]
		print(json.dumps(result, ensure_ascii=False))
	else:
		if args.nocolor:
			print(f"{title}: {count}")
		else:
			print(f"{title}: {get_color(count, ref)}{count}{Colors.END}")

if __name__ == "__main__":
	main()