"""Simple Firebird moderation bot.

This bot watches message events and demonstrates a practical moderation loop.
Give the token these intents: messages, message_content, reactions, moderation.
Give the token these permissions: view_channels, read_messages, send_messages,
manage_messages, timeout_members, view_audit_log.

Try in chat:
  !modhelp
  !timeout 42 10m please cool down
"""

import re

from firebird_bot import BotClient, FirebirdAPIError


bot = BotClient()
BLOCKED_WORDS = {"scamlink", "free-nitro"}
TIME_RE = re.compile(r"^(?P<num>\d+)(?P<unit>[smhd])$")


def parse_duration(text):
    match = TIME_RE.match(text.strip().lower())
    if not match:
        return 10 * 60
    num = int(match.group("num"))
    unit = match.group("unit")
    return num * {"s": 1, "m": 60, "h": 3600, "d": 86400}[unit]


@bot.command("modhelp")
def help_command(ctx):
    ctx.reply("Moderation commands: !timeout <user_id> <10m> <reason>. I also remove a few demo blocked words.")


@bot.command("timeout")
def timeout_command(ctx):
    parts = ctx.args.split(maxsplit=2)
    if len(parts) < 2:
        ctx.reply("Usage: !timeout <user_id> <10m> [reason]")
        return
    target_user_id = int(parts[0])
    seconds = parse_duration(parts[1])
    reason = parts[2] if len(parts) > 2 else "Timed out by moderation bot"
    ctx.timeout(target_user_id, seconds=seconds, reason=reason)
    ctx.reply(f"Timed out user {target_user_id} for {seconds // 60 or 1} minute(s).")


@bot.event("message_create")
def check_message(event):
    message = event.message
    content = (message.get("content") or "").lower()
    if not content:
        return
    if any(word in content for word in BLOCKED_WORDS):
        try:
            bot.delete_message(message["id"])
            bot.send_message(
                f"Removed a message from {message.get('author')} for a blocked phrase.",
                server_id=event.server_id,
                channel_id=event.channel_id,
            )
        except FirebirdAPIError as exc:
            print(f"Could not remove message {message.get('id')}: {exc}")


@bot.event("reaction_add")
def log_reaction(event):
    payload = event.payload
    print(f"Reaction {payload.get('emoji')} added to message {payload.get('message_id')}")


if __name__ == "__main__":
    bot.run_forever()
