from datetime import datetime
from pytz import timezone
from app.bot.utils.tg_escape_chars import escape_telegram_chars

def format_trigger_message(trigger, zabbix_url: str) -> str:
    tz = timezone('Europe/Moscow')
    priority_map = {'4': 'HIGH', '5': 'DISASTER'}

    event_time_epoch = int(trigger.get('lastEvent', {}).get('clock', trigger.get('lastchange', 0)))
    event_time = datetime.fromtimestamp(event_time_epoch, tz=tz)
    event_time_formatted = event_time.strftime('%Y-%m-%d %H:%M:%S Мск')

    host = trigger.get('hosts', [{}])[0].get('name', 'Неизвестно')
    priority = priority_map.get(str(trigger.get('priority')), 'Неизвестно')
    description = escape_telegram_chars(trigger.get('description', '')).replace("{HOST.NAME}", host)

    items = trigger.get('items', [])
    item_ids = [item['itemid'] for item in items]

    for i, item in enumerate(items):
        placeholder = f"{{ITEM.LASTVALUE{i + 1}}}"
        if placeholder in description:
            description = description.replace(placeholder, item.get('lastvalue', '?'))

    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"

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