# -*- coding: utf-8 -*-
# Centauria Script pour WeeChat (Linux et macOS) : noyau.
# Adapte du Centauria Script pour mIRC (base sur Babylon Script 6.0 de Vlad, adapte par Laurent).
# Reseau : irc.centauria.fr, port 6697, SSL (UnrealIRCd + services Anope).
# Licence : fourni tel quel, sans garantie.
#
# Installation : copier ce fichier dans ~/.local/share/weechat/python/ (ou ~/.weechat/python/),
# puis dans WeeChat :  /script load centauria.py   (autoload : lien dans python/autoload/)
# Tapez /cs aide pour la liste des commandes.

import re
import time

try:
    import weechat
except ImportError:  # permet de tester la logique hors de WeeChat
    weechat = None

NAME = "centauria"
VERSION = "1.0.0"
AUTHOR = "Laurent (Centauria)"
DESC = "Centauria Script : fonctions du script mIRC adaptees a WeeChat"
VERSION_URL = "https://centauria.fr/downloads/weechat-version.txt"
PAGE_URL = "https://centauria.fr/script-mirc/"

DEFAULTS = {
    "usermodes": "",          # ex. +ixR : modes personnels remis a chaque connexion
    "nspass": "",             # mot de passe NickServ (facultatif ; preferer SASL, voir README)
    "autojoin": "",           # salons separes par des virgules, tries
    "founder": "",            # salons pour lesquels envoyer ChanServ UP
    "hl.words": "",           # mots surveilles (virgules)
    "hl.bell": "on",          # bip sur mot surveille / pseudo
    "ecr.fautes": "off",      # correcteur de fautes a l'envoi
    "ecr.rac": "off",         # raccourcis (bjr -> bonjour) a l'envoi
    "split.known": "",        # serveurs connus (detection de split)
    "update.auto": "on",      # verification de version au chargement
    "keys": "on",             # touches F7 (kick), F8 (kick+ban), F9 (ban)
}

FAUTES = {
    "ca": "ça", "cest": "c'est", "jai": "j'ai", "jsuis": "je suis", "jsais": "je sais",
    "jvais": "je vais", "jveux": "je veux", "jpeux": "je peux", "sava": "ça va",
    "kan": "quand", "kand": "quand", "keske": "qu'est-ce que", "pourkoi": "pourquoi",
    "pourqoi": "pourquoi", "pourquoit": "pourquoi", "enfaite": "en fait", "deja": "déjà",
    "tres": "très", "apres": "après", "etre": "être", "meme": "même", "voila": "voilà",
    "bientot": "bientôt", "ecole": "école",
}
RACCOURCIS = {
    "bjr": "bonjour", "bsr": "bonsoir", "svp": "s'il vous plaît", "dsl": "désolé",
    "bcp": "beaucoup", "pk": "pourquoi", "qd": "quand", "tjrs": "toujours",
    "pb": "problème", "mnt": "maintenant", "tlm": "tout le monde",
    "cad": "c'est-à-dire", "pr": "pour",
}
EXPRESSIONS = {
    "a tous": "à tous", "a toutes": "à toutes", "a bientot": "à bientôt",
    "a demain": "à demain", "sa va": "ça va",
}

SERVICES = {"ns": "NickServ", "cs": "ChanServ", "bs": "BotServ", "ms": "MemoServ", "hs": "HostServ"}

AIDE = [
    "Centauria Script pour WeeChat " + VERSION,
    "/cs aide                      cette aide",
    "/cs modes [+ixR|off]          modes personnels remis a chaque connexion",
    "/cs ident [mot de passe|off]  identification NickServ automatique (voir README pour SASL)",
    "/cs autojoin [add|del|list] #salon   salons rejoints a la connexion (tries)",
    "/cs founder [add|del|list] #salon    ChanServ UP automatique (droits fondateur)",
    "/cs hl [add|del|list] mot     mots surveilles ; /cs hl bell on|off",
    "/cs kick pseudo [raison]      F7 : kick",
    "/cs kb pseudo [raison]        F8 : ban + kick",
    "/cs ban pseudo                F9 : ban",
    "/cs scan texte [-k]           cherche un domaine dans les adresses du salon (-k : kick+ban)",
    "/cs split [-r]                detecte un split de serveurs (-r : nouvelle reference)",
    "/cs ns|cs|bs|ms|hs <texte>    envoie aux services (NickServ, ChanServ, BotServ, MemoServ, HostServ)",
    "/cs ecriture [fautes|raccourcis] on|off   correcteur d'ecriture a l'envoi",
    "/cs update                    verifie s'il existe une nouvelle version",
]


# ---------------------------------------------------------------- utilitaires
def say(msg, buf=""):
    weechat.prnt(buf, "[Centauria] " + msg)


def opt(name):
    if weechat.config_is_set_plugin(name):
        return weechat.config_get_plugin(name)
    return DEFAULTS.get(name, "")


def setopt(name, value):
    weechat.config_set_plugin(name, value)


def is_on(name):
    return opt(name).lower() in ("on", "1", "oui", "true")


def is_centauria(server):
    addrs = weechat.config_string(weechat.config_get("irc.server.%s.addresses" % server)) or ""
    return "centauria.fr" in addrs.lower() or "centauria" in server.lower()


def split_list(text):
    return [x for x in re.split(r"[,\s]+", text) if x]


def join_list(items):
    return ",".join(sorted(set(items), key=str.lower))


def list_cmd(buf, optname, args, label):
    """Gere 'add|del|list' pour une liste stockee dans une option."""
    parts = args.split(None, 1)
    action = parts[0].lower() if parts else "list"
    value = parts[1].strip() if len(parts) > 1 else ""
    items = split_list(opt(optname))
    if action == "add" and value:
        items += split_list(value)
        setopt(optname, join_list(items))
        say("%s : %s" % (label, opt(optname)), buf)
    elif action == "del" and value:
        gone = [v.lower() for v in split_list(value)]
        setopt(optname, join_list([i for i in items if i.lower() not in gone]))
        say("%s : %s" % (label, opt(optname) or "(vide)"), buf)
    else:
        say("%s : %s" % (label, opt(optname) or "(vide)"), buf)
    return optname


# ---------------------------------------------------------------- ecriture
def _case_like(orig, new):
    if orig[:1].isupper() and not orig.isupper():
        return new[:1].upper() + new[1:]
    if orig.isupper() and len(orig) > 1:
        return new.upper()
    return new


def fix_text(text, fautes=True, raccourcis=True):
    """Corrige un message : mots (fautes, raccourcis) puis expressions. Ignore URL, #salons, @pseudos."""
    if not (fautes or raccourcis):
        return text
    tokens = re.split(r"(\s+)", text)
    out = []
    for tok in tokens:
        if not tok or tok.isspace() or "://" in tok or tok[0] in "#@&/" or "\x01" in tok:
            out.append(tok)
            continue
        m = re.match(r"^([^\w']*)([\w']+)([^\w']*)$", tok, re.UNICODE)
        if not m:
            out.append(tok)
            continue
        pre, word, post = m.groups()
        key = word.lower()
        new = None
        if raccourcis and key in RACCOURCIS:
            new = RACCOURCIS[key]
        elif fautes and key in FAUTES:
            new = FAUTES[key]
        out.append(pre + (_case_like(word, new) if new else word) + post)
    res = "".join(out)
    if fautes:
        for k, v in EXPRESSIONS.items():
            res = re.sub(r"(?<!\w)" + re.escape(k) + r"(?!\w)",
                         lambda mm, v=v: _case_like(mm.group(0), v), res, flags=re.I)
    return res


def out_privmsg_cb(data, modifier, server, string):
    f, r = is_on("ecr.fautes"), is_on("ecr.rac")
    if not (f or r) or not is_centauria(server):
        return string
    m = re.match(r"^(PRIVMSG \S+ :)(.*)$", string, re.S)
    if not m or m.group(2).startswith("\x01"):
        return string
    return m.group(1) + fix_text(m.group(2), f, r)


# ---------------------------------------------------------------- connexion
def sig_001_cb(data, signal, signal_data):
    server = signal.split(",")[0]
    if not is_centauria(server):
        return weechat.WEECHAT_RC_OK
    modes = opt("usermodes")
    if modes:
        weechat.command(_server_buffer(server), "/mode %s %s" % (weechat.info_get("irc_nick", server), modes))
    if opt("nspass"):
        weechat.command(_server_buffer(server), "/msg NickServ IDENTIFY " + opt("nspass"))
    weechat.hook_timer(3000, 0, 1, "autojoin_timer_cb", server)
    return weechat.WEECHAT_RC_OK


def _server_buffer(server):
    return weechat.buffer_search("irc", "server." + server)


def autojoin_timer_cb(server, remaining):
    chans = split_list(opt("autojoin"))
    if chans:
        weechat.command(_server_buffer(server), "/join -server %s %s" % (server, ",".join(sorted(chans, key=str.lower))))
    return weechat.WEECHAT_RC_OK


def founder_up(server, channel=None):
    chans = [c for c in split_list(opt("founder")) if channel is None or c.lower() == channel.lower()]
    for c in chans:
        weechat.command(_server_buffer(server), "/msg ChanServ UP " + c)


def sig_join_cb(data, signal, signal_data):
    server = signal.split(",")[0]
    if not is_centauria(server):
        return weechat.WEECHAT_RC_OK
    info = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data})
    if info.get("nick") == weechat.info_get("irc_nick", server):
        founder_up(server, info.get("channel") or info.get("text"))
    return weechat.WEECHAT_RC_OK


def sig_900_cb(data, signal, signal_data):
    server = signal.split(",")[0]
    if is_centauria(server):
        founder_up(server)
    return weechat.WEECHAT_RC_OK


# ---------------------------------------------------------------- highlight
def apply_highlight():
    weechat.config_set_plugin("hl.words", opt("hl.words"))
    words = split_list(opt("hl.words"))
    weechat.command("", "/set weechat.look.highlight \"%s\"" % ",".join(words))


def bell():
    try:
        with open("/dev/tty", "w") as tty:
            tty.write("\a")
            tty.flush()
    except OSError:
        pass


def print_cb(data, buf, date, tags, displayed, highlight, prefix, message):
    if highlight and is_on("hl.bell"):
        bell()
    return weechat.WEECHAT_RC_OK


# ---------------------------------------------------------------- moderation
def current_chan(buf):
    if weechat.buffer_get_string(buf, "localvar_type") != "channel":
        return None, None
    return weechat.buffer_get_string(buf, "localvar_server"), weechat.buffer_get_string(buf, "localvar_channel")


def nick_host(server, chan, nick):
    infolist = weechat.infolist_get("irc_nick", "", "%s,%s,%s" % (server, chan, nick))
    host = ""
    if infolist:
        while weechat.infolist_next(infolist):
            host = weechat.infolist_string(infolist, "host")
        weechat.infolist_free(infolist)
    return host


def do_kick(buf, nick, reason, ban):
    server, chan = current_chan(buf)
    if not chan:
        say("A utiliser dans un salon.", buf)
        return
    if ban:
        weechat.command(buf, "/kickban %s %s" % (nick, reason or "Banni"))
    else:
        weechat.command(buf, "/kick %s %s" % (nick, reason or "Kick"))


def do_ban(buf, nick):
    server, chan = current_chan(buf)
    if not chan:
        say("A utiliser dans un salon.", buf)
        return
    weechat.command(buf, "/ban " + nick)


def do_scan(buf, text, kick):
    server, chan = current_chan(buf)
    if not chan:
        say("A utiliser dans un salon.", buf)
        return
    text = text.lower()
    me = weechat.info_get("irc_nick", server)
    found = 0
    infolist = weechat.infolist_get("irc_nick", "", "%s,%s" % (server, chan))
    hits = []
    if infolist:
        while weechat.infolist_next(infolist):
            nick = weechat.infolist_string(infolist, "name")
            host = weechat.infolist_string(infolist, "host")
            if text in ("%s!%s" % (nick, host)).lower():
                hits.append((nick, host, weechat.infolist_string(infolist, "prefixes")))
        weechat.infolist_free(infolist)
    for nick, host, prefixes in hits:
        found += 1
        say("  %s (%s)" % (nick, host or "adresse inconnue"), buf)
        if kick and nick != me and not prefixes.strip():
            weechat.command(buf, "/kickban %s Scan de domaine" % nick)
    say("%d utilisateur(s) de %s trouve(s)." % (found, text), buf)


def do_split(buf, reset):
    server = weechat.buffer_get_string(buf, "localvar_server")
    if reset:
        setopt("split.known", "")
        say("Split : liste des serveurs reinitialisee.", buf)
        return
    if not server:
        say("A utiliser dans un buffer de serveur ou de salon.", buf)
        return
    STATE["split"] = {"server": server, "buf": buf, "now": []}
    weechat.command(_server_buffer(server), "/quote LINKS")
    weechat.hook_timer(8000, 0, 1, "split_done_cb", "")


STATE = {"split": None}


def sig_364_cb(data, signal, signal_data):
    st = STATE["split"]
    if st and signal.split(",")[0] == st["server"]:
        parts = signal_data.split()
        if len(parts) > 3:
            st["now"].append(parts[3])
    return weechat.WEECHAT_RC_OK


def split_done_cb(data, remaining):
    st = STATE["split"]
    STATE["split"] = None
    if not st:
        return weechat.WEECHAT_RC_OK
    now, buf = sorted(set(st["now"])), st["buf"]
    old = split_list(opt("split.known"))
    if not old:
        setopt("split.known", ",".join(now))
        say("Split : %d serveurs enregistres comme reference." % len(now), buf)
        return weechat.WEECHAT_RC_OK
    lost = [s for s in old if s not in now]
    gain = [s for s in now if s not in old]
    if gain:
        setopt("split.known", ",".join(sorted(set(old + gain))))
        say("Split : nouveau(x) serveur(s) : " + " ".join(gain), buf)
    if lost:
        say("SPLIT detecte : serveur(s) absent(s) du reseau : %s. Les utilisateurs de ces serveurs ont quitte." % " ".join(lost), buf)
    else:
        say("Aucun split : les %d serveurs connus sont presents." % len(now), buf)
    return weechat.WEECHAT_RC_OK


# ---------------------------------------------------------------- touches
def bind_keys(on):
    keys = {"meta2-18~": "kick", "meta2-19~": "kb", "meta2-20~": "ban"}  # F7, F8, F9
    for k, cmd in keys.items():
        if on:
            weechat.command("", "/key bind %s /input insert /cs %s " % (k, cmd))
        else:
            weechat.command("", "/key unbind " + k)


# ---------------------------------------------------------------- mise a jour
def cmp_ver(a, b):
    pa = [int(x) for x in re.findall(r"\d+", a)]
    pb = [int(x) for x in re.findall(r"\d+", b)]
    return (pa > pb) - (pa < pb)


def update_check(manual):
    weechat.hook_process_hashtable("url:" + VERSION_URL, {"timeout": "10000"}, 15000,
                                   "update_cb", "manual" if manual else "auto")


def update_cb(data, command, rc, out, err):
    if rc != 0:
        if data == "manual":
            say("Verification impossible (reseau).")
        return weechat.WEECHAT_RC_OK
    lines = [l.strip() for l in out.splitlines() if l.strip()]
    if lines and cmp_ver(lines[0], VERSION) > 0:
        say("Mise a jour disponible : %s (installee : %s). %s" % (lines[0], VERSION, PAGE_URL))
        if len(lines) > 2:
            say("Nouveautes : " + lines[2])
    elif data == "manual":
        say("Vous avez la derniere version (%s)." % VERSION)
    return weechat.WEECHAT_RC_OK


# ---------------------------------------------------------------- commande /cs
def cs_cb(data, buf, args):
    parts = args.split(None, 1)
    sub = parts[0].lower() if parts else "aide"
    rest = parts[1].strip() if len(parts) > 1 else ""

    if sub in ("aide", "help", "?"):
        for l in AIDE:
            say(l, buf)
    elif sub == "modes":
        if rest.lower() == "off":
            setopt("usermodes", "")
        elif rest:
            setopt("usermodes", rest)
        say("Modes personnels : %s" % (opt("usermodes") or "(aucun)"), buf)
    elif sub == "ident":
        if rest.lower() == "off":
            setopt("nspass", "")
            say("Identification automatique desactivee.", buf)
        elif rest:
            setopt("nspass", rest)
            say("Identification automatique activee.", buf)
        else:
            say("Identification automatique : %s" % ("activee" if opt("nspass") else "desactivee"), buf)
    elif sub == "autojoin":
        list_cmd(buf, "autojoin", rest, "Auto-join")
    elif sub == "founder":
        list_cmd(buf, "founder", rest, "Auto-founder")
    elif sub == "hl":
        p = rest.split()
        if p and p[0].lower() == "bell":
            setopt("hl.bell", "on" if len(p) < 2 or p[1].lower() == "on" else "off")
            say("Bip : " + opt("hl.bell"), buf)
        else:
            list_cmd(buf, "hl.words", rest, "Mots surveilles")
            apply_highlight()
    elif sub in ("kick", "kb", "ban"):
        p = rest.split(None, 1)
        if not p:
            say("Usage : /cs %s pseudo [raison]" % sub, buf)
        elif sub == "ban":
            do_ban(buf, p[0])
        else:
            do_kick(buf, p[0], p[1] if len(p) > 1 else "", sub == "kb")
    elif sub == "scan":
        kick = rest.endswith(" -k")
        text = rest[:-3].strip() if kick else rest
        if text:
            do_scan(buf, text, kick)
        else:
            say("Usage : /cs scan texte [-k]", buf)
    elif sub == "split":
        do_split(buf, rest == "-r")
    elif sub in SERVICES:
        if rest:
            weechat.command(buf, "/msg %s %s" % (SERVICES[sub], rest))
        else:
            weechat.command(buf, "/msg %s HELP" % SERVICES[sub])
    elif sub == "ecriture":
        p = rest.lower().split()
        if len(p) == 2 and p[0] in ("fautes", "raccourcis") and p[1] in ("on", "off"):
            setopt("ecr.fautes" if p[0] == "fautes" else "ecr.rac", p[1])
        say("Ecriture : fautes %s, raccourcis %s" % (opt("ecr.fautes"), opt("ecr.rac")), buf)
    elif sub == "update":
        update_check(True)
    else:
        say("Commande inconnue. /cs aide", buf)
    return weechat.WEECHAT_RC_OK


# ---------------------------------------------------------------- demarrage
def main():
    if not weechat.register(NAME, AUTHOR, VERSION, "GPL3", DESC, "", ""):
        return
    for k, v in DEFAULTS.items():
        if not weechat.config_is_set_plugin(k):
            weechat.config_set_plugin(k, v)
    weechat.hook_command(
        "cs", "Centauria Script", "aide | modes | ident | autojoin | founder | hl | kick | kb | ban | scan | split | ns | cs | bs | ms | hs | ecriture | update",
        "Tapez /cs aide",
        "aide || modes || ident || autojoin || founder || hl || kick || kb || ban || scan || split"
        " || ns || cs || bs || ms || hs || ecriture fautes|raccourcis on|off || update",
        "cs_cb", "")
    weechat.hook_signal("*,irc_in2_001", "sig_001_cb", "")
    weechat.hook_signal("*,irc_in2_JOIN", "sig_join_cb", "")
    weechat.hook_signal("*,irc_in2_900", "sig_900_cb", "")
    weechat.hook_signal("*,irc_in2_364", "sig_364_cb", "")
    weechat.hook_modifier("irc_out1_PRIVMSG", "out_privmsg_cb", "")
    weechat.hook_print("", "notify_highlight", "", 0, "print_cb", "")
    if is_on("keys"):
        bind_keys(True)
    if split_list(opt("hl.words")):
        apply_highlight()
    if is_on("update.auto"):
        update_check(False)
    say("Centauria Script %s charge. /cs aide" % VERSION)


if weechat is not None:
    main()
