"""Lightweight User-Agent parser. Avoids extra deps for basic classification."""
import re

_BOT_PAT = re.compile(r"bot|crawl|spider|slurp|mediapartners|facebookexternalhit|preview|monitor", re.I)
_MOBILE_PAT = re.compile(r"mobi|iphone|android.*mobile|ipod", re.I)
_TABLET_PAT = re.compile(r"ipad|tablet|android(?!.*mobile)", re.I)


def parse_ua(ua: str) -> dict:
    if not ua:
        return {"device": "unknown", "os": "", "browser": ""}

    if _BOT_PAT.search(ua):
        device = "bot"
    elif _TABLET_PAT.search(ua):
        device = "tablet"
    elif _MOBILE_PAT.search(ua):
        device = "mobile"
    else:
        device = "desktop"

    os = ""
    if "Windows" in ua:
        os = "Windows"
    elif "Mac OS X" in ua or "Macintosh" in ua:
        os = "macOS"
    elif "Android" in ua:
        os = "Android"
    elif "iPhone" in ua or "iPad" in ua or "iOS" in ua:
        os = "iOS"
    elif "Linux" in ua:
        os = "Linux"
    elif "CrOS" in ua:
        os = "ChromeOS"

    browser = ""
    # Order matters: more-specific UAs first.
    if "Edg/" in ua:
        browser = "Edge"
    elif "OPR/" in ua or "Opera" in ua:
        browser = "Opera"
    elif "Chrome/" in ua and "Chromium" not in ua:
        browser = "Chrome"
    elif "Firefox/" in ua:
        browser = "Firefox"
    elif "Safari/" in ua:
        browser = "Safari"

    return {"device": device, "os": os, "browser": browser}
