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

# --------------------------------------------------------------------------- #
#    Isida-NG Jabber Bot (fork of iSida)                                      #
#    Isida-NG Copyright (C) 2026 Luciferus <luciferus@ubunix.pro>             #
#                                                                             #
#    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/>.    #
#                                                                             #
#    Project home: https://git.ubunix.pro/Luciferus/isida-ng                                #
# --------------------------------------------------------------------------- #

import os
import subprocess
import hashlib
import datetime
import re

QR_DIR = data_folder % 'qr/'
QR_URL = pasteurl + 'qr/'
QR_SIZE = 350

# --------------------------------------------------------------------------- #
# ПРОВЕРКА QRENCODE                                                           #
# --------------------------------------------------------------------------- #

def _check_qrencode():
    """Проверяет наличие qrencode и возвращает команду установки."""
    try:
        subprocess.run(['qrencode', '--version'], capture_output=True, check=True)
        return True, None
    except (subprocess.CalledProcessError, FileNotFoundError):
        # Определяем менеджер пакетов
        if os.path.exists('/usr/bin/apt') or os.path.exists('/usr/bin/apt-get'):
            return False, 'sudo apt install qrencode'
        elif os.path.exists('/usr/bin/dnf'):
            return False, 'sudo dnf install qrencode'
        elif os.path.exists('/usr/bin/yum'):
            return False, 'sudo yum install qrencode'
        elif os.path.exists('/usr/bin/zypper'):
            return False, 'sudo zypper install qrencode'
        elif os.path.exists('/usr/bin/pacman'):
            return False, 'sudo pacman -S qrencode'
        else:
            return False, 'qrencode (install from your package manager)'

# --------------------------------------------------------------------------- #
# QR-ГЕНЕРАТОР                                                               #
# --------------------------------------------------------------------------- #

def _ensure_qr_dir():
    if not os.path.exists(QR_DIR):
        try:
            os.makedirs(QR_DIR)
        except:
            return False
    return True

def _generate_qr(text):
    """Генерирует QR-код и возвращает URL."""
    if not _ensure_qr_dir():
        return None

    filename = hashlib.md5(text.encode('utf-8')).hexdigest() + '.png'
    full_path = os.path.join(QR_DIR, filename)
    url = QR_URL + filename

    if os.path.exists(full_path):
        return url

    cmd = ['qrencode', '-o', full_path, '-s', str(QR_SIZE // 10), '-m', '2', '-l', 'M', text]
    try:
        subprocess.run(cmd, capture_output=True, timeout=5, check=True)
        return url if os.path.exists(full_path) else None
    except:
        return None

# --------------------------------------------------------------------------- #
# ФОРМИРОВАНИЕ ДАННЫХ ДЛЯ QR                                                  #
# --------------------------------------------------------------------------- #

def _format_wifi(ssid, password):
    """WIFI:T:WPA;S:MyWiFi;P:MyPassword;;"""
    return f"WIFI:T:WPA;S:{ssid};P:{password};;"

def _format_vcard(name, phone, email):
    """vCard"""
    return f"""BEGIN:VCARD
VERSION:3.0
FN:{name}
TEL:{phone}
XMPP:{jid}
EMAIL:{email}
END:VCARD"""

def _format_geo(lat, lon):
    """geo:45.7505,47.6174"""
    return f"geo:{lat},{lon}"

def _format_cal(summary, start, end, location=''):
    """iCalendar"""
    start_dt = datetime.datetime.fromisoformat(start.replace('Z', '+00:00'))
    end_dt = datetime.datetime.fromisoformat(end.replace('Z', '+00:00'))
    start_str = start_dt.strftime('%Y%m%dT%H%M%S')
    end_str = end_dt.strftime('%Y%m%dT%H%M%S')
    return f"""BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SUMMARY:{summary}
DTSTART:{start_str}
DTEND:{end_str}
LOCATION:{location if location else 'XMPP'}
END:VEVENT
END:VCALENDAR"""

# --------------------------------------------------------------------------- #
# КОМАНДА QR                                                                 #
# --------------------------------------------------------------------------- #

def qr_cmd(type, jid, nick, text):
    text = text.strip()
    if not text:
        send_msg(type, jid, nick, L('What?', '%s/%s' % (jid, nick)))
        return

    # Проверяем qrencode
    has, install_cmd = _check_qrencode()
    if not has:
        msg = L('qrencode not installed.\nInstall it: %s', '%s/%s' % (jid, nick)) % install_cmd
        send_msg(type, jid, nick, msg)
        return

    parts = text.split()
    cmd = parts[0].lower()
    qr_text = None

    # --- wifi ---
    if cmd == 'wifi' and len(parts) >= 3:
        ssid = parts[1]
        password = ' '.join(parts[2:])
        qr_text = _format_wifi(ssid, password)
        desc = L('Wi-Fi: %s', '%s/%s' % (jid, nick)) % ssid

    # --- vcard ---
    elif cmd == 'vcard' and len(parts) >= 4:
        name = parts[1]
        phone = parts[2]
        xmpp = parts[3]
        email = parts[4]
        qr_text = _format_vcard(name, phone, email)
        desc = L('Contact: %s', '%s/%s' % (jid, nick)) % name

    # --- geo ---
    elif cmd == 'geo' and len(parts) >= 3:
        lat = parts[1]
        lon = parts[2]
        qr_text = _format_geo(lat, lon)
        desc = L('Coordinates: %s, %s', '%s/%s' % (jid, nick)) % (lat, lon)

    # --- cal ---
    elif cmd == 'cal' and len(parts) >= 5:
        summary = parts[1]
        start = parts[2]
        end = parts[3]
        location = ' '.join(parts[4:]) if len(parts) > 4 else ''
        qr_text = _format_cal(summary, start, end, location)
        desc = L('Event: %s', '%s/%s' % (jid, nick)) % summary

    # --- text / url (простой текст) ---
    else:
        qr_text = text
        desc = L('QR for: %s', '%s/%s' % (jid, nick)) % text[:50]

    if not qr_text:
        send_msg(type, jid, nick, L('Error: invalid format. Use: qr <type> <params>', '%s/%s' % (jid, nick)))
        return

    url = _generate_qr(qr_text)
    if url:
        msg = L('%s\n%s', '%s/%s' % (jid, nick)) % (desc, url)
    else:
        msg = L('Failed to generate QR-code', '%s/%s' % (jid, nick))

    send_msg(type, jid, nick, msg)

# --------------------------------------------------------------------------- #
# HELP (короткая справка)                                                     #
# --------------------------------------------------------------------------- #

def qr_help(type, jid, nick, text):
    msg = L('QR-code generator.\n'
            'Usage:\n'
            '  qr wifi <SSID> <password> - Wi-Fi QR\n'
            '  qr vcard <name> <phone> <xmpp> <email> - contact\n'
            '  qr geo <lat> <lon> - location\n'
            '  qr cal <title> <start> <end> [location] - event\n'
            '  qr <text|url> - any text/URL\n'
            'Examples:\n'
            '  qr wifi MyWiFi MyPassword\n'
            '  qr vcard Name +79001234567 user@server.tld\n'
            '  qr geo 45.7505 47.6174\n'
            '  qr cal "Meeting" 2026-08-15T10:00 2026-08-15T12:00 "Office"\n'
            '  qr https://server.tld\n'
            'Dates: YYYY-MM-DDTHH:MM (e.g. 2026-08-15T10:00)',
            '%s/%s' % (jid, nick))
    send_msg(type, jid, nick, msg)

# --------------------------------------------------------------------------- #
# REGISTER COMMANDS                                                           #
# --------------------------------------------------------------------------- #

execute = [
    (3, 'qr', qr_cmd, 2, 'Generate QR-code. See "qr help" for details.'),
    (3, 'qr help', qr_help, 2, 'Show QR help.'),
]
