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

# --------------------------------------------------------------------------- #
#                                                                             #
#    Plugin for iSida Jabber Bot                                              #
#    Copyright (C) ferym <luciferus@ubunix.pro>                                #
#    Modified by: Your Name                                                  #
#                                                                             #
#    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 decode_js_string(s):
    """Decode JavaScript string literal content (without surrounding quotes) into a Python string."""
    result = []
    i = 0
    while i < len(s):
        if s[i] == '\\' and i + 1 < len(s):
            nc = s[i + 1]
            if nc == '"':
                result.append('"')
                i += 2
            elif nc == '\\':
                result.append('\\')
                i += 2
            elif nc == 'n':
                result.append('\n')
                i += 2
            elif nc == 'r':
                result.append('\r')
                i += 2
            elif nc == 't':
                result.append('\t')
                i += 2
            elif nc == '/':
                result.append('/')
                i += 2
            else:
                result.append(s[i])
                i += 1
        else:
            result.append(s[i])
            i += 1
    return ''.join(result)

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

        # Ищем 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 (в JS-нотации с экранированием кавычек)
        json_string = json_match.group(1)

        # Декодируем JS-экранированные символы (\" -> ", \\ -> \, \n -> newline, etc.)
        json_string = decode_js_string(json_string)

        # Чистим от HTML-тегов и управляющих символов
        json_string = re.sub(r'<br\s*/?>', '\n', json_string)
        json_string = re.sub(r'[\x00-\x1f\x7f]', '', json_string)

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

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

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

        # Чистим от лишних пробелов
        message = 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:
        # Если нужно, можно залогировать ошибку
        # log_error(str(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')]
