import re
from dataclasses import dataclass
from typing import Optional, Union


@dataclass
class ParsedCommand:
    action: str
    value: Optional[Union[str, int]] = None


def parse_voice_command(raw_command: str) -> ParsedCommand:
    command = raw_command.strip().lower()
    if not command:
        return ParsedCommand(action="unknown")

    if command.startswith("play "):
        query = command.replace("play", "", 1).strip()
        return ParsedCommand(action="play", value=query)
    if command == "play":
        return ParsedCommand(action="play", value="")

    if any(word in command for word in ("exit", "quit", "goodbye")):
        return ParsedCommand(action="exit")

    if any(word in command for word in ("pause", "stop")):
        return ParsedCommand(action="pause")

    if any(word in command for word in ("resume", "continue", "unpause")):
        return ParsedCommand(action="resume")

    if any(word in command for word in ("next", "skip")):
        return ParsedCommand(action="next")

    if any(word in command for word in ("previous", "go back", "back track")):
        return ParsedCommand(action="previous")

    if "volume up" in command or "louder" in command:
        return ParsedCommand(action="volume_delta", value=10)

    if "volume down" in command or "quieter" in command:
        return ParsedCommand(action="volume_delta", value=-10)

    volume_match = re.search(r"(?:set )?volume(?: to)?\s+(\d{1,3})", command)
    if volume_match:
        return ParsedCommand(action="volume_set", value=int(volume_match.group(1)))

    if any(word in command for word in ("what is playing", "now playing", "current song")):
        return ParsedCommand(action="now_playing")

    return ParsedCommand(action="unknown")
