from datetime import datetime

from pytz import timezone

from app.bot.utils.tg_escape_chars import escape_telegram_chars
from config import ZABBIX_URL, ZABBIX_TZ


def format_trigger_for_tg(trigger):
    """
    Формирует текст сообщения для одного триггера
    и возвращает (text, inline_buttons_data)
    """
    priority_map = {'4': 'HIGH', '5': 'DISASTER'}
    priority_map_emoji = {'4': '⚠️','5': '⛔️'}
    event_time_epoch = int(trigger['lastEvent']['clock'])
    event_time = datetime.fromtimestamp(event_time_epoch, tz=timezone(ZABBIX_TZ))
    event_time_formatted = event_time.strftime('%Y-%m-%d %H:%M:%S Мск')

    description = escape_telegram_chars(trigger['description'])
    host = trigger['hosts'][0]['name']
    priority = priority_map.get(trigger['priority'], 'Неизвестно')
    icon = priority_map_emoji.get(trigger['priority'], 'Неизвестно')
    description = description.replace("{HOST.NAME}", host)
    for i, item in enumerate(trigger['items']):
        placeholder = f"{{ITEM.LASTVALUE{i + 1}}}"
        if placeholder in description:
            description = description.replace(placeholder, item['lastvalue'])

    item_ids = [item['itemid'] for item in trigger['items']]
    batchgraph_link = f"{ZABBIX_URL}/history.php?action=batchgraph&"
    batchgraph_link += "&".join([f"itemids[{item_id}]={item_id}" for item_id in item_ids])
    batchgraph_link += "&graphtype=0"

    text = (
        f"<b>Host</b>: {host}\n"
        f"<b>Описание</b>: {description}\n"
        f"<b>Критичность</b>: {icon} {priority}\n"
        f"<b>Время создания</b>: {event_time_formatted}\n"
        # f'<b>URL</b>: <a href="{batchgraph_link}">Ссылка на график</a>'
    )

    # Возвращаем текст и ссылку, чтобы потом сделать inline кнопку
    return text, batchgraph_link
