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

# --------------------------------------------------------------------------- #
#                                                                             #
#    Plugin for iSida Jabber Bot                                              #
#    Copyright (C) Vit@liy <vitaliy@root.ua>                                  #
#    Modified by: Fixed quotes from skio.ru                                   #
#    Last modified by Luciferus: complete code change                         #
#                                                                             #
#    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 random
import time
import json

# Список тем с skio.ru
THEMES = {
    'biz': 'Бизнес',
    'gratitude': 'Благодарность',
    'rich': 'Богатство и бедность',
    'family': 'Брак и семья',
    'war': 'Война',
    'sin': 'Грех',
    'kids': 'Детство, дети',
    'friend': 'Дружба',
    'life': 'Жизнь',
    'health': 'Здоровье и медицина',
    'beauty': 'Красота',
    'love': 'Любовь',
    'world': 'Мироздание',
    'wisdom': 'Мудрость',
    'menwomen': 'Мужчина и женщина',
    'science': 'Наука',
    'ingratitude': 'Неблагодарность',
    'hate': 'Ненависть',
    'edu': 'Образование',
    'pessimism': 'Пессимизм',
    'politics': 'Политика',
    'truth': 'Правда и ложь',
    'religion': 'Религия',
    'glory': 'Слава и известность',
    'death': 'Смерть и бессмертие',
    'happy': 'Счастье',
    'work': 'Труд',
    'human': 'Человек',
    'reading': 'Чтение и книги',
    'humour': 'Юмористические афоризмы',
    'en': 'На английском языке',
}

# Список авторов (тоже темы)
AUTHORS = {
    'zhvanecky': 'Михаил Жванецкий',
    'prutkov': 'Козьма Прутков',
    'ranevskaya': 'Фаина Раневская',
    'svetlov': 'Михаил Светлов',
    'ushinsky': 'Константин Ушинский',
}

# Объединяем все темы
ALL_THEMES = dict(THEMES)
ALL_THEMES.update(AUTHORS)

# Алиасы для обратной совместимости
ALIASES = {
    'aphorism': 'wisdom',
    'aphorisms': 'wisdom',
    'afor': 'wisdom',
}

# Кэш для цитат
_quotes_cache = {}
_quotes_cache_time = {}

def get_quotes_from_theme(theme_key):
    """
    Получает список цитат по теме с skio.ru
    """
    global _quotes_cache, _quotes_cache_time

    # Проверяем кэш (обновляем раз в час)
    current_time = time.time()
    if theme_key in _quotes_cache and (current_time - _quotes_cache_time.get(theme_key, 0)) < 3600:
        return _quotes_cache[theme_key]

    try:
        url = 'https://skio.ru/quotes/%s_quotes.php' % theme_key

        # Загружаем страницу через load_page
        data = load_page(url)

        # Декодируем если нужно
        if isinstance(data, bytes):
            data = data.decode('utf-8', errors='ignore')
        elif data is None:
            return None

        # Ищем цитаты
        # Формат: <div class="qtext">&#128395; Текст<br><span class="qauthor">Автор</span></div>
        pattern = r'<div class="qtext">.*?&#128395;\s*(.*?)<br><span class="qauthor">(.*?)</span></div>'
        matches = re.findall(pattern, data, re.S)

        if not matches:
            return None

        quotes = []
        for text, author in matches:
            # Чистим текст
            text = text.strip()
            text = re.sub(r'<[^>]+>', '', text)
            text = re.sub(r'\s+', ' ', text)

            # Чистим автора
            author = author.strip()
            author = re.sub(r'<[^>]+>', '', author)
            author = re.sub(r'\s+', ' ', author)

            if text and len(text) > 3:
                if author:
                    quotes.append('%s — %s' % (text, author))
                else:
                    quotes.append(text)

        if quotes:
            _quotes_cache[theme_key] = quotes
            _quotes_cache_time[theme_key] = current_time
            return quotes

        return None

    except Exception as e:
        return None

def get_random_quote(theme_key=None):
    """
    Возвращает случайную цитату
    Если theme_key=None - выбирает случайную тему
    """
    if theme_key is None:
        available = list(ALL_THEMES.keys())
        if not available:
            return None, None
        theme_key = random.choice(available)

    # Проверяем алиасы
    if theme_key in ALIASES:
        theme_key = ALIASES[theme_key]

    # Проверяем, существует ли тема
    if theme_key not in ALL_THEMES:
        return None, None

    quotes = get_quotes_from_theme(theme_key)
    if not quotes:
        return None, None

    return random.choice(quotes), theme_key

def quote(type, jid, nick, text):
    """
    Основная команда quote
    Форматы:
    - quote list - список тем
    - quote - случайная цитата
    - quote [тема] - цитата из темы
    """
    try:
        text = text.strip().lower()

        # Список тем
        if text == 'list':
            msg = L('Available themes:', '%s/%s' % (jid, nick))
            themes = []
            for key, title in sorted(ALL_THEMES.items()):
                themes.append('• %s (%s)' % (title, key))
            msg += '\n' + '\n'.join(themes)
            send_msg(type, jid, nick, msg)
            return

        # Если есть параметр - ищем тему
        if text:
            # Проверяем алиасы
            if text in ALIASES:
                text = ALIASES[text]

            # Проверяем точное совпадение
            if text in ALL_THEMES:
                quote_text, theme_key = get_random_quote(text)
                if quote_text:
                    msg = '%s (%s)' % (quote_text, ALL_THEMES[theme_key])
                else:
                    msg = L('No quotes found in theme "%s".', '%s/%s' % (jid, nick)) % ALL_THEMES[text]
            else:
                # Ищем частичное совпадение по названию
                found = None
                for key, title in ALL_THEMES.items():
                    if text in key.lower() or text in title.lower():
                        found = key
                        break

                if found:
                    quote_text, theme_key = get_random_quote(found)
                    if quote_text:
                        msg = '%s (%s)' % (quote_text, ALL_THEMES[found])
                    else:
                        msg = L('No quotes found in theme "%s".', '%s/%s' % (jid, nick)) % ALL_THEMES[found]
                else:
                    msg = L('Theme "%s" not found. Use "quote list" to see available themes.', '%s/%s' % (jid, nick)) % text
        else:
            # Случайная цитата из случайной темы
            quote_text, theme_key = get_random_quote()
            if quote_text and theme_key:
                msg = '%s (%s)' % (quote_text, ALL_THEMES[theme_key])
            else:
                msg = L('No quotes found. Try "quote list" to see available themes.', '%s/%s' % (jid, nick))

        send_msg(type, jid, nick, msg)

    except Exception as e:
        send_msg(type, jid, nick, L('Something broken.', '%s/%s' % (jid, nick)))

def afor(type, jid, nick):
    """Команда afor - случайный афоризм (для обратной совместимости)"""
    quote(type, jid, nick, 'wisdom')

global execute

execute = [
    (3, 'quote', quote, 2, 'Quote from skio.ru.\nquote list - list of themes\nquote - random quote\nquote [theme] - random quote from theme'),
    (3, 'afor', afor, 1, 'Show random aphorism'),
]
