"""
Type d'appareil, systeme et navigateur a partir du User-Agent.

Les indications client (Sec-CH-UA-*) completent le User-Agent quand le
navigateur les envoie : Chrome et Edge ne distinguent Windows 11 de Windows 10
et ne donnent le modele d'un telephone Android que par ce canal (le
middleware les demande avec l'en-tete Accept-CH).
"""

import hashlib
import re

ORDINATEUR = "ORDINATEUR"
TELEPHONE = "TELEPHONE"
TABLETTE = "TABLETTE"
ROBOT = "ROBOT"
INCONNU = "INCONNU"

_ROBOTS = re.compile(
    r"bot\b|bot/|crawl|spider|slurp|curl/|wget/|python-requests|python-urllib|httpclient|okhttp|"
    r"headlesschrome|uptime|monitor|go-http-client|postman",
    re.I,
)
_WINDOWS = {"10.0": "10", "6.3": "8.1", "6.2": "8", "6.1": "7", "6.0": "Vista", "5.1": "XP"}

# (motif, nom) dans l'ordre : Edge et Opera se declarent aussi "Chrome".
_NAVIGATEURS = (
    (re.compile(r"(?:Edg|EdgA|EdgiOS)/(\d+)"), "Edge"),
    (re.compile(r"(?:OPR|Opera)/(\d+)"), "Opera"),
    (re.compile(r"SamsungBrowser/(\d+)"), "Samsung Internet"),
    (re.compile(r"YaBrowser/(\d+)"), "Yandex"),
    (re.compile(r"(?:Firefox|FxiOS)/(\d+)"), "Firefox"),
    (re.compile(r"CriOS/(\d+)"), "Chrome"),
    (re.compile(r"Chrome/(\d+)"), "Chrome"),
    (re.compile(r"Version/(\d+)[\d.]* (?:Mobile/\S+ )?Safari/"), "Safari"),
    (re.compile(r"(?:MSIE |Trident/.*rv:)(\d+)"), "Internet Explorer"),
)


def _indication(meta, nom):
    return str(meta.get(f"HTTP_SEC_CH_UA_{nom}", "") or "").strip().strip('"')


def _systeme(ua, meta):
    plateforme = _indication(meta, "PLATFORM")
    version = _indication(meta, "PLATFORM_VERSION")
    majeure = version.split(".")[0] if version else ""

    match = re.search(r"Windows NT (\d+\.\d+)", ua)
    if match or plateforme == "Windows":
        nt = match.group(1) if match else "10.0"
        if nt == "10.0":
            # Windows 11 annonce une version de plateforme >= 13 (indication client).
            if majeure.isdigit():
                return "Windows 11" if int(majeure) >= 13 else "Windows 10"
            return "Windows 10/11"
        return f"Windows {_WINDOWS.get(nt, nt)}"
    match = re.search(r"Android (\d+(?:\.\d+)?)", ua)
    if match:
        return f"Android {majeure or match.group(1)}"
    match = re.search(r"(?:iPhone|iPad|iPod).*? OS (\d+)_(\d+)", ua)
    if match:
        return f"iOS {match.group(1)}.{match.group(2)}"
    if "CrOS" in ua:
        return "ChromeOS"
    match = re.search(r"Mac OS X (\d+)[_.](\d+)", ua)
    if match or plateforme == "macOS":
        if majeure.isdigit():
            return f"macOS {majeure}"
        return f"macOS {match.group(1)}.{match.group(2)}" if match else "macOS"
    if "Ubuntu" in ua:
        return "Ubuntu"
    if "Linux" in ua or plateforme == "Linux":
        return "Linux"
    return plateforme


def _navigateur(ua):
    for motif, nom in _NAVIGATEURS:
        match = motif.search(ua)
        if match:
            return f"{nom} {match.group(1)}"
    return ""


def _appareil(ua, meta):
    if _ROBOTS.search(ua):
        return ROBOT
    if "iPad" in ua or "Tablet" in ua or ("Android" in ua and "Mobile" not in ua):
        return TABLETTE
    # iPadOS se presente comme un Mac, mais garde le jeton "Mobile/".
    if "Macintosh" in ua and "Mobile/" in ua:
        return TABLETTE
    if _indication(meta, "MOBILE") == "?1" or re.search(r"Mobi|iPhone|iPod|Windows Phone", ua):
        return TELEPHONE
    if re.search(r"Windows|Macintosh|X11|CrOS|Linux", ua):
        return ORDINATEUR
    return INCONNU


def _modele(ua, meta):
    modele = _indication(meta, "MODEL")
    if modele:
        return modele[:100]
    for nom in ("iPhone", "iPad", "iPod"):
        if nom in ua:
            return nom
    match = re.search(r"Android [\d.]+; (?:[a-z]{2}[-_][a-zA-Z]{2}; )?([^;)]+?)(?: Build/|\))", ua)
    # Chrome reduit le User-Agent Android a "K" : le modele vient alors de Sec-CH-UA-Model.
    if match and match.group(1).strip() not in {"K", "wv"}:
        return match.group(1).strip()[:100]
    return ""


def analyser(user_agent, meta=None):
    """
    Description lisible de l'appareil.

    Retourne {appareil, systeme, navigateur, modele, empreinte}. L'empreinte
    (type + famille de systeme + famille de navigateur + modele) ignore les
    numeros de version : une mise a jour du navigateur n'est pas un nouvel appareil.
    """

    ua = str(user_agent or "")
    meta = meta or {}
    systeme = _systeme(ua, meta)
    navigateur = _navigateur(ua)
    appareil = _appareil(ua, meta)
    modele = _modele(ua, meta)
    famille = "|".join([
        appareil,
        systeme.split(" ")[0] if systeme else "",
        navigateur.rsplit(" ", 1)[0] if navigateur else "",
        modele,
    ])
    return {
        "appareil": appareil,
        "systeme": systeme[:100],
        "navigateur": navigateur[:100],
        "modele": modele,
        "empreinte": hashlib.sha1(famille.encode("utf-8")).hexdigest(),
    }
