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

# --------------------------------------------------------------------------- #
#    Isida-NG Jabber Bot (fork of iSida)                                      #
#    Original iSida Copyright (C) 2009-2015 diSabler <dsy@dsy.name>           #
#    Isida-NG Copyright (C) 2026 Luciferus <luciferus@ubunix.pro>             #
#    Project home: https://git.ubunix.pro/Luciferus/isida-ng                  #
#                                                                             #
#    Looking for holidays and reasons to get drunk plugin                     #
#                                                                             #
#    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/>.    #
#                                                                             #
# --------------------------------------------------------------------------- #

# translate: first,second,third,fourth,fifth,sixth,seventh,eighth,nineth,tenth,eleventh,twelveth,thirteenth,fourteenth,fivteenth,sixteenth,seventeenth,eighteenth,nineteenth,twentieth,twenty-first,twenty-second,twenty-third,twenty-fourth,twenty-fifth,twenty-sixth,twenty-seventh,twenty-eighth,twenty-nineth,thirtieth,thirty-first,january,february,march,april,may,june,july,august,september,october,november,december,January,February,March,April,May,June,July,August,September,October,November,December,monday,tuesday,wendesday,thirsday,friday,saturday,sunday,last,last,Last,last,Last,Last,lAst

drink_dmas = ['first','second','third','fourth','fifth','sixth','seventh','eighth','nineth','tenth','eleventh','twelveth',
            'thirteenth','fourteenth','fivteenth','sixteenth','seventeenth','eighteenth','nineteenth','twentieth',
            'twenty-first','twenty-second','twenty-third','twenty-fourth','twenty-fifth','twenty-sixth','twenty-seventh',
            'twenty-eighth','twenty-nineth','thirtieth','thirty-first']
drink_mmas1 = ['january','february','march','april','may','june','july','august','september','october','november','december']
drink_mmas2 = ['January','February','March','April','May','June','July','August','September','October','November','December']
drink_wday = ['monday','tuesday','wendesday','thirsday','friday','saturday','sunday']
drink_lday = ['last','last','Last','last','Last','Last','lAst']

def to_drink(type, jid, nick, text):
    text = (text or '').strip()
    # Today or a concrete date (D.DD) -> fetch real holidays for that date from calend.ru
    if re.match(r'\d+\.\d+$', text) or len(text) <= 2:
        calend(type, jid, nick, text)
        return
    # Otherwise treat the argument as a holiday name and look it up in the local DB
    if os.path.isfile(date_file):
        ddate = readfile(date_file)
        or_text = text
        msg = ''
        if not ddate:
            msg = L('Read file error.','%s/%s'%(jid,nick))
        else:
            for tmp in ddate.split('\n'):
                if or_text and or_text.lower() in tmp.lower(): msg += '\n'+tmp
            if msg == '': msg = L('Holiday: %s not found.','%s/%s'%(jid,nick)) % or_text
            else: msg = L('I know holidays: %s','%s/%s'%(jid,nick)) % msg
    else: msg = L('Database doesn\'t exist.','%s/%s'%(jid,nick))
    send_msg(type, jid, nick, msg)

import urllib.request

_CAL_BASE = 'https://www.calend.ru'
_CAL_UA = 'Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0'

def _calend_load(url):
    req = urllib.request.Request(url, headers={
        'User-Agent': _CAL_UA,
        'Accept': 'text/html,application/xhtml+xml',
        'Accept-Language': 'ru-RU,ru;q=0.9,en;q=0.8'})
    try:
        with urllib.request.urlopen(req, timeout=15) as r:
            raw = r.read()
    except Exception:
        return ''
    m = re.findall(rb'charset=["\']?([0-9a-zA-Z\-]+)', raw[:4096])
    enc = m[-1].decode('ascii', 'replace') if m else 'utf-8'
    try:
        return raw.decode(enc, 'replace')
    except (LookupError, UnicodeDecodeError):
        try:
            return raw.decode('utf-8', 'replace')
        except Exception:
            return ''

def _calend_names(data):
    seen = set()
    names = []
    for name in re.findall(r'<span class="title"><a href="(?:https?://www\.calend\.ru)?/holidays/0/0/\d+/"[^>]*>([^<]+)</a>', data):
        name = re.sub(r'\s+', ' ', name).strip()
        if name and name not in seen:
            seen.add(name)
            names.append(name)
    return names

def _calend_header(data):
    og = re.search(r'<meta property="og:title" content="([^"]+)"', data)
    if og:
        return re.sub(r'^Праздники\s+', '', og.group(1), count=1).strip()
    t = get_tag(data, 'title')
    if t:
        return t.split(' - ')[0].strip()
    return ''

def calend(type, jid, nick, text):
    msg, url, text = '', '', text.strip()
    if not text:
        lt = tuple(time.localtime())[1:3]
        url = '%s/holidays/%s-%s/' % (_CAL_BASE, lt[0], lt[1])
    elif re.match(r'\d+\.\d+$', text):
        parts = text.split('.')
        url = '%s/holidays/%s-%s/' % (_CAL_BASE, parts[1], parts[0])
    elif len(text) > 1: url = '%s/search/?search_str=' % _CAL_BASE + urllib.parse.quote(text.encode('cp1251'))
    if url:
        data = _calend_load(url)
        if data:
            hl = _calend_names(data)
            if hl:
                if '/search/' in url:
                    d = text
                else:
                    d = _calend_header(data) or get_tag(data, 'h1')
                    d = re.sub(r'<[^>]+>', '', d).strip()
                msg = '%s:\n%s' % (d, '\n'.join(hl))
    else: msg = L('What?','%s/%s'%(jid,nick))
    if not msg: msg = L('Holiday: %s not found.','%s/%s'%(jid,nick)) % text
    send_msg(type, jid, nick, msg)

global execute

execute = [(3, 'drink', to_drink, 2, 'Find holiday\ndrink [name_holiday/date]',['raw']),
        (3, 'calend', calend, 2, 'Find holiday\ncalend [name_holiday/date]')]
