import re
from typing import Dict, Any

import misskey

import config
from custom_types import ParsedNotification


def parse_notification(
        notification: Dict[str, Any],
        client: misskey.Misskey) -> ParsedNotification | None:
    '''Parses any notifications received by the bot'''

    # Get the full Activitypub ID of the user
    user = notification.get("user", {})
    username = user.get("username", "unknown")
    host = user.get("host")
    # Local users may not have a hostname attached
    full_user = f"@{username}" if not host else f"@{username}@{host}"

    note_obj = notification.get("note", {})
    note_text = note_obj.get("text")
    note_id = note_obj.get("id")

    note = note_text.strip().lower() if note_text else ""
    # Split words into tokens
    parts = note.split()

    # Check for both short and fully-qualified name mentions
    username_variants = [
        config.USER,
        f'@{config.USER.split("@")[1]}'
    ]

    # Notifs must consist of the initial mention and at least one other token
    if len(parts) <= 1:
        return None

    # Make sure the first token is a mention to the bot
    if not parts[0] in username_variants:
        return None

    command = parts[1].lower()
    arguments = parts[2:] if len(parts) > 2 else []

    return {
        'author': full_user,
        'command': command,
        'arguments': arguments,
        'note_obj': note_obj
    }