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

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

def get_max_freq():
	"""Получение максимальной частоты CPU"""
	freq_file = '/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq'
	try:
		with open(freq_file, 'r') as f:
			freq_khz = int(f.read().strip())
			return freq_khz / 1_000  # Convert to MHz
	except:
		try:
			output = subprocess.check_output(['lscpu'], text=True)
			for line in output.split('\n'):
				if 'max MHz' in line.lower():
					freq_mhz = float(line.split(':')[1].strip())
					return freq_mhz
			sys.exit(1)
		except:
			print(f"Ошибка: Не удалось открыть файл {freq_file}")
			print("Ошибка: Не удалось получить максимальную частоту CPU при помощи lscpu")
			sys.exit(1)

def get_color(freq, limit=3000):
	"""Получение цвета для частоты"""
	half_limit = limit * 1.5
	if freq > limit*1.5:
		return Colors.GREEN
	elif freq >= 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 = 3000
	title = f"Максимальная частота процессора (не менее {ref} MHz)"	
	cpu_freq = get_max_freq()

	if cpu_freq is None:
		print("Ошибка: Не удалось получить максимальную частоту CPU")
		sys.exit(1)
	
	if args.json:
		result = [{
			"title": title,
			"value": cpu_freq,
			"reference": ref,
			"format": "{x:.0f} MHz",
			"condition": "greater"
		}]
		print(json.dumps(result, ensure_ascii=False))
	else:
		if args.nocolor:
			print(f"{title}: {cpu_freq}")
		else:
			print(f"{title}: {get_color(cpu_freq, ref)}{cpu_freq}{Colors.END}")

if __name__ == "__main__":
	main()