"""
FastTGBot - суперпростой Telegram бот
"""

import telebot
from telebot.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove

# Глобальные переменные
_bot_instance = None
_handlers = []

class FastTGBot:
    def __init__(self, token):
        global _bot_instance
        self.bot = telebot.TeleBot(token)
        _bot_instance = self
        
        # Автоматический /start
        @self.bot.message_handler(commands=['start'])
        def start_command(m):
            self.bot.send_message(m.chat.id, "✅ Бот запущен!")
        
        # Обработчик всех сообщений
        @self.bot.message_handler(func=lambda m: True)
        def handle_message(m):
            for condition, action in _handlers:
                if condition == m.text or (callable(condition) and condition(m.text)):
                    if callable(action):
                        action(m)
                    else:
                        self.bot.send_message(m.chat.id, str(action))
    
    def run(self):
        print("✅ Бот запущен!")
        self.bot.infinity_polling()

# ========== ОСНОВНЫЕ ==========

def ifm(condition, action):
    """Если сообщение = condition"""
    _handlers.append((condition, action))
    return condition

def snd(text):
    """Отправить сообщение"""
    def _send(m):
        _bot_instance.bot.send_message(m.chat.id, text)
    return _send

# ========== КНОПКИ ==========

def btn(text, action):
    """Одна кнопка"""
    ifm(text, action)
    def _btn(m):
        markup = ReplyKeyboardMarkup(resize_keyboard=True)
        markup.add(KeyboardButton(text))
        _bot_instance.bot.send_message(m.chat.id, "👇", reply_markup=markup)
    return _btn

def btns(buttons, action):
    """Несколько кнопок"""
    for b in buttons:
        ifm(b, action)
    def _btns(m):
        markup = ReplyKeyboardMarkup(resize_keyboard=True)
        for b in buttons:
            markup.add(KeyboardButton(b))
        _bot_instance.bot.send_message(m.chat.id, "👇", reply_markup=markup)
    return _btns

def inb(text, data, action):
    """Инлайн кнопка"""
    @_bot_instance.bot.callback_query_handler(func=lambda call: call.data == data)
    def cb(call):
        if callable(action):
            action(call.message)
        else:
            _bot_instance.bot.send_message(call.message.chat.id, str(action))
        _bot_instance.bot.answer_callback_query(call.id)
    
    def _inb(m):
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton(text, callback_data=data))
        _bot_instance.bot.send_message(m.chat.id, "👇", reply_markup=markup)
    return _inb

def inbs(buttons, action):
    """Несколько инлайн кнопок"""
    for txt, data in buttons:
        @_bot_instance.bot.callback_query_handler(func=lambda call, d=data: call.data == d)
        def cb(call, d=data):
            if callable(action):
                action(call.message)
            else:
                _bot_instance.bot.send_message(call.message.chat.id, str(action))
            _bot_instance.bot.answer_callback_query(call.id)
    
    def _inbs(m):
        markup = InlineKeyboardMarkup()
        for txt, data in buttons:
            markup.add(InlineKeyboardButton(txt, callback_data=data))
        _bot_instance.bot.send_message(m.chat.id, "👇", reply_markup=markup)
    return _inbs

def clr():
    """Убрать кнопки"""
    def _clr(m):
        _bot_instance.bot.send_message(m.chat.id, "✅", reply_markup=ReplyKeyboardRemove())
    return _clr

# ========== МЕДИА ==========

def pic(photo):
    """Отправить фото"""
    def _pic(m):
        if photo.startswith('http'):
            _bot_instance.bot.send_photo(m.chat.id, photo)
        else:
            with open(photo, 'rb') as f:
                _bot_instance.bot.send_photo(m.chat.id, f)
    return _pic

# ========== ДЕЙСТВИЯ ==========

def wait(sec, action):
    """Подождать"""
    import time
    def _wait(m):
        time.sleep(sec)
        if callable(action):
            action(m)
        else:
            _bot_instance.bot.send_message(m.chat.id, str(action))
    return _wait

# ========== AI ГЕНЕРАЦИЯ ==========

def ai(prompt, api_key):
    """
    Генерирует код функции по описанию
    
    Пример:
        code = ai("кнопка бебебе пишет привет", "твой_ключ")
        exec(code)
    """
    from mistralai import Mistral
    
    docs = """
    Функции:
    - ifm("текст", snd("ответ"))
    - btn("кнопка", snd("действие"))
    - btns(["кнопка1","кнопка2"], snd("ок"))
    - inb("текст", "data", snd("ок"))
    - pic("фото.jpg")
    - wait(5, snd("прошло"))
    - clr()
    """
    
    try:
        client = Mistral(api_key=api_key)
        response = client.chat.complete(
            model="mistral-small-latest",
            messages=[
                {"role": "system", "content": f"Ты генератор кода для fasttgbot. Вот функции:\n{docs}\nОтвечай ТОЛЬКО кодом."},
                {"role": "user", "content": prompt}
            ]
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"# Ошибка: {e}"

__version__ = "0.2.0"