package com.yaoyuan.jiscuss.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Lightweight User-Agent parser.
 * Extracts a human-readable browser name and major version without
 * importing a heavy third-party library.
 *
 * <p>Detection order matters: Edge must be checked before Chrome, and
 * Chrome before Safari, because UA strings commonly contain multiple tokens.
 */
public final class UserAgentUtils {

    private UserAgentUtils() {}

    private static final Pattern EDGE    = Pattern.compile("Edg(?:e|A|iOS)?/([\\d.]+)", Pattern.CASE_INSENSITIVE);
    private static final Pattern FIREFOX = Pattern.compile("Firefox/([\\d.]+)", Pattern.CASE_INSENSITIVE);
    private static final Pattern CHROME  = Pattern.compile("Chrome/([\\d.]+)", Pattern.CASE_INSENSITIVE);
    private static final Pattern SAFARI  = Pattern.compile("Version/([\\d.]+).*Safari", Pattern.CASE_INSENSITIVE);
    private static final Pattern OPERA   = Pattern.compile("OPR/([\\d.]+)", Pattern.CASE_INSENSITIVE);
    private static final Pattern IE      = Pattern.compile("(?:MSIE |Trident/.*rv:)([\\d.]+)", Pattern.CASE_INSENSITIVE);

    /**
     * Returns a short browser description, e.g. "Chrome 120", "Firefox 121", "Safari 17".
     * Returns "未知浏览器" when detection fails.
     *
     * @param userAgent the raw User-Agent header value
     * @return display string, never null
     */
    public static String parseBrowser(String userAgent) {
        if (userAgent == null || userAgent.isBlank()) {
            return "未知浏览器";
        }
        // Order matters: Edge contains 'Chrome', Chrome contains 'Safari'
        String r;
        if ((r = match(EDGE,    userAgent, "Edge"))    != null) return r;
        if ((r = match(OPERA,   userAgent, "Opera"))   != null) return r;
        if ((r = match(FIREFOX, userAgent, "Firefox")) != null) return r;
        if ((r = match(CHROME,  userAgent, "Chrome"))  != null) return r;
        if ((r = match(SAFARI,  userAgent, "Safari"))  != null) return r;
        if ((r = match(IE,      userAgent, "IE"))       != null) return r;
        return "未知浏览器";
    }

    private static String match(Pattern pattern, String ua, String name) {
        Matcher m = pattern.matcher(ua);
        if (m.find()) {
            String version = m.group(1);
            // Only keep major version number
            int dotIdx = version.indexOf('.');
            String major = dotIdx > 0 ? version.substring(0, dotIdx) : version;
            return name + " " + major;
        }
        return null;
    }
}
