import rrdtool
import time
import requests
from dotenv import load_dotenv
import os

load_dotenv()

def send_telegram(min_temp, min_time, max_temp, max_time):
    token = os.getenv("TELEGRAM_TOKEN")
    channel_id = os.getenv("TELEGRAM_CHANNEL_ID")
    if not token or not channel_id:
        raise ValueError("Telegram токен или ID канала не заданы в .env")

    # Форматируем текст комментария
    comment = (
        f"Min Temp: {min_temp:.2f}°C at {min_time}\n"
        f"Max Temp: {max_temp:.2f}°C at {max_time}"
    )

    url = f"https://api.telegram.org/bot{token}/sendPhoto"
    with open('temperature_graph.png', 'rb') as file:
        r = requests.post(url, data={
            "chat_id": channel_id,
            "caption": comment  # Текст комментария
        }, files={
            "photo": file
        })
    print(r.text)
    if r.status_code != 200:
        raise Exception(f"Ошибка отправки в Telegram: {r.text}")


def get_extreme_timestamps(rrd_file: str, start_time: int, end_time: int):
    # Извлекаем данные из RRD-файла
    info = rrdtool.fetch(rrd_file, 'AVERAGE', '--start', str(start_time), '--end', str(end_time))
    data = info[2]  # Сырые данные
    timestamps = range(info[0][0], info[0][1], info[0][2])  # Генерация временных меток

    # Поиск минимального и максимального значений
    min_low_temp, max_high_temp = float('inf'), float('-inf')
    min_low_time, max_high_time = None, None

    for idx, row in enumerate(data):
        if row[0] is not None:  # Проверяем, что данные не отсутствуют
            if row[0] < min_low_temp:
                min_low_temp = row[0]
                min_low_time = timestamps[idx]
            if row[1] is not None and row[1] > max_high_temp:
                max_high_temp = row[1]
                max_high_time = timestamps[idx]

    return min_low_temp, min_low_time, max_high_temp, max_high_time


def create_graph(rrd_file: str, output_file: str):
    # Получаем текущее время
    now = int(time.time())
    start_time = now - 86400  # 24 часа назад
    start_date = time.strftime("%d-%m-%Y", time.localtime(start_time))
    end_date = time.strftime("%d-%m-%Y", time.localtime(now))

    # Получаем минимальные и максимальные значения с временными метками
    min_low_temp, min_low_time, max_high_temp, max_high_time = get_extreme_timestamps(rrd_file, start_time, now)

    # Форматирование времени
    min_low_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(min_low_time))
    max_high_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(max_high_time))

    # Вывод значений в терминал
    print(f"\033[32m{'Min Temp:':<20}\033[0m{min_low_temp:>10.2f}°C at {min_low_time_str}")
    print(f"\033[31m{'Max Temp:':<20}\033[0m{max_high_temp:>10.2f}°C at {max_high_time_str}")

    try:
        rrdtool.graph(
            output_file,
            "--start", str(start_time),
            "--end", str(now),
            "--title", f"Temperature from {start_date} to {end_date}",
            "--vertical-label", "Temperature (°C)",
            "--width", "800",
            "--height", "400",
            # Определение данных
            "DEF:low_temp={}:temp_low:AVERAGE".format(rrd_file),
            "DEF:high_temp={}:temp_high:AVERAGE".format(rrd_file),
            # Линии графика
            "LINE1:low_temp#0000FF:Low Temperature",
            "LINE2:high_temp#FF0000:Top Temperature",
            # Вертикальные линии для экстремумов
            f"VRULE:{min_low_time}#00FF00:Min Temp Time",
            f"VRULE:{max_high_time}#FF0000:Max Temp Time",

            # Подписи
            "COMMENT: \\n",
            r"GPRINT:low_temp:MIN:Min Low Temp\: %2.2lf°C",
            "COMMENT: \\n",
            r"GPRINT:high_temp:MAX:Max Top Temp\: %2.2lf°C",
            "COMMENT: \\n",
            r"GPRINT:low_temp:AVERAGE:Avg Low Temp\: %2.2lf°C",
            "COMMENT: \\n",
            r"GPRINT:high_temp:AVERAGE:Avg Top Temp\: %2.2lf°C"
        )
        print(f"График успешно создан: {output_file}")
        send_telegram(min_low_temp, min_low_time_str, max_high_temp, max_high_time_str)
    except Exception as e:
        print(f"Ошибка создания графика: {e}")


# Пример использования
rrd_file = "temperature_data.rrd"
output_file = "temperature_graph.png"
create_graph(rrd_file, output_file)
