#!/usr/bin/python
# -*- coding: utf-8 -*-

# --------------------------------------------------------------------------- #
#                                                                             #
#    Plugin for iSida Jabber Bot                                              #
#    Copyright (C) Luciferus <luciferus@ubunix.pro>                           #
#    Fixed by: Proper JSON parsing from anekdot.ru                           #
#                                                                             #
#    This program is free software: you can redistribute it and/or modify     #
#    it under the terms of the GNU General Public License as published by     #
#    the Free Software Foundation, either version 3 of the License, or        #
#    (at your option) any later version.                                      #
#                                                                             #
#    This program is distributed in the hope that it will be useful,          #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU General Public License for more details.                             #
#                                                                             #
#    You should have received a copy of the GNU General Public License        #
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.    #
#                                                                             #
# --------------------------------------------------------------------------- #

import re
import json
import random

def anek(type, jid, nick):
    try:
        # Загружаем страницу с JS-скриптом (UTF-8 версия)
        target = load_page('https://www.anekdot.ru/rss/randomu.html')

        # Если load_page возвращает bytes - декодируем в строку
        if isinstance(target, bytes):
            target = target.decode('utf-8', errors='ignore')

        # Ищем JSON-массив с анекдотами
        # В скрипте он выглядит как: var anekdot_texts = JSON.parse('[...]');
        # Используем жадный поиск, чтобы захватить ВЕСЬ массив
        json_match = re.search(r"var anekdot_texts = JSON\.parse\('(.*?)'\);", target, re.DOTALL)

        if not json_match:
            raise Exception('JSON not found')

        # Получаем строку JSON с экранированием
        json_string = json_match.group(1)

        # Декодируем JS-строку (экранирование кавычек, слэшей и пр.)
        # В JSON от anekdot.ru используются: \", \\, \/, \n, \r, \t
        json_string = json_string.replace('\\"', '"')   # \"
        json_string = json_string.replace('\\\\', '\\') # \\
        json_string = json_string.replace('\\/', '/')   # \/
        json_string = json_string.replace('\\n', '\n')  # \n
        json_string = json_string.replace('\\r', '\r')  # \r
        json_string = json_string.replace('\\t', '\t')  # \t

        # Убираем управляющие символы, которые могут сломать JSON
        json_string = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', json_string)

        # Парсим JSON
        texts = json.loads(json_string)

        if not texts:
            raise Exception('No anecdotes found')

        # Выбираем случайный анекдот
        message = random.choice(texts)

        # Чистим от HTML-тегов (если остались)
        message = re.sub(r'<[^>]+>', '', message)

        # Чистим от лишних пробелов и переносов
        message = re.sub(r'\s+', ' ', message).strip()

        # Отправляем
        if type == 'groupchat':
            if len(message) < GT('anek_private_limit'):
                send_msg(type, jid, nick, message)
            else:
                send_msg(type, jid, nick, L('Send for you in private', '%s/%s' % (jid, nick)))
                send_msg('chat', jid, nick, message)
                return
        else:
            send_msg(type, jid, nick, message)

    except Exception as e:
        # Отправляем сообщение об ошибке пользователю
        send_msg(type, jid, nick, L('Something broken.', '%s/%s' % (jid, nick)))

global execute

execute = [(3, 'anek', anek, 1, 'Show random anecdote from anekdot.ru | Modified')]
