import re

from rollbot import as_command, Attachment, Command
from rollbot.injection import Args, ArgList, SenderName, Origin

# RGYBbPO
SQUARES = ["🟥", "🟩", "🟨", "🟦", "🟫", "🟪", "🟧"]
HEARTS = ["❤️", "💚", "💛", "💙", "🤎", "💜", "🧡"]

# Title best effort search
TITLE_PAT = re.compile(r"\s*[tT]itle:\s*(.+)")


@as_command
def poll(origin: Origin, name: SenderName, args: Args, arg_list: ArgList, cmd: Command):
    if origin != "DISCORD":
        return "Polls only supported in Discord!"

    for delim in ("|", ";", ","):
        if delim in args:
            opts = args.split(delim)
            break
    else:
        opts = arg_list

    i, title = next(
        ((i, m.group(1)) for i, o in enumerate(opts) if (m := TITLE_PAT.match(o))),
        (-1, None),
    )
    if title:
        del opts[i]

    emojis = HEARTS + SQUARES if cmd.name == "pollhearts" else SQUARES + HEARTS

    if len(opts) > len(emojis):
        return f"Polls are limited to {len(emojis)} options! Hardware limitation :\\("

    if len(opts) == 0:
        return "Can't make an empty poll!"

    msg = f"Poll started by {name}\n\n"
    if title:
        msg += f"**{title}**\n"
    atts = []
    for e, o in zip(emojis, opts):
        msg += f"> {e} - **{o.strip()}**\n"
        atts.append(Attachment(name="react", body=e))
    msg += "\nPlease participate in democracy by picking the emojis corresponding to your choices!"
    return msg, *atts, Attachment(name="pin", body=None)
