package cn.novalon.gym.manage.sys.util;

import org.springframework.stereotype.Component;

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

/**
 * User-Agent解析工具类
 * 
 * 用于解析HTTP请求头中的User-Agent信息，提取浏览器类型、版本和操作系统信息
 * 
 * @author 张翔
 * @date 2026-03-24
 */
@Component
public class UserAgentParser {

    private static final Pattern BROWSER_PATTERN = Pattern.compile(
            "(Chrome|Firefox|Safari|Edge|MSIE|Trident|Opera)[/\\s]([\\d.]+)");

    /**
     * 解析User-Agent字符串，返回浏览器信息
     * 
     * @param userAgent User-Agent字符串
     * @return 浏览器名称和版本，如"Chrome 120.0"
     */
    public String parseBrowser(String userAgent) {
        if (userAgent == null || userAgent.isEmpty()) {
            return "未知浏览器";
        }

        Matcher matcher = BROWSER_PATTERN.matcher(userAgent);
        if (matcher.find()) {
            return matcher.group(1) + " " + matcher.group(2);
        }

        return "未知浏览器";
    }

    /**
     * 解析User-Agent字符串，返回操作系统信息
     * 
     * @param userAgent User-Agent字符串
     * @return 操作系统名称和版本，如"Windows 10"或"Mac OS X"
     */
    public String parseOS(String userAgent) {
        if (userAgent == null || userAgent.isEmpty()) {
            return "未知系统";
        }

        String ua = userAgent;

        if (ua.contains("Windows NT 10.0")) {
            return "Windows 10";
        } else if (ua.contains("Windows NT 6.3")) {
            return "Windows 8.1";
        } else if (ua.contains("Windows NT 6.2")) {
            return "Windows 8";
        } else if (ua.contains("Windows NT 6.1")) {
            return "Windows 7";
        } else if (ua.contains("Windows NT")) {
            return "Windows";
        } else if (ua.contains("Mac OS X")) {
            return "Mac OS X";
        } else if (ua.contains("Linux")) {
            return "Linux";
        } else if (ua.contains("Android")) {
            return "Android";
        } else if (ua.contains("iPhone")) {
            return "iPhone";
        } else if (ua.contains("iPad")) {
            return "iPad";
        } else if (ua.contains("iPod")) {
            return "iPod";
        }

        return "未知系统";
    }

    /**
     * 解析User-Agent字符串，返回浏览器和操作系统信息
     * 
     * @param userAgent User-Agent字符串
     * @return 格式化的浏览器和操作系统信息
     */
    public String parseUserAgent(String userAgent) {
        if (userAgent == null || userAgent.isEmpty()) {
            return "未知浏览器 / 未知系统";
        }
        return parseBrowser(userAgent) + " / " + parseOS(userAgent);
    }
}