package session

import "strings"

// DeviceInfo 从 User-Agent 解析出的设备摘要信息
type DeviceInfo struct {
	Device  string // 设备类型：Desktop / Mobile / Tablet
	OS      string // 操作系统：Windows 10 / macOS / Android 12 等
	Browser string // 浏览器：Chrome 120 / Firefox 121 / Safari 17 等
}

// ParseUA 从原始 User-Agent 字符串解析设备信息（轻量级，不引入第三方库）
func ParseUA(ua string) DeviceInfo {
	info := DeviceInfo{Device: "Desktop"}

	lower := strings.ToLower(ua)

	// --- 操作系统 ---
	switch {
	case strings.Contains(lower, "windows nt 10"):
		info.OS = "Windows 10/11"
	case strings.Contains(lower, "windows nt 6.3"):
		info.OS = "Windows 8.1"
	case strings.Contains(lower, "windows nt 6.2"):
		info.OS = "Windows 8"
	case strings.Contains(lower, "windows nt 6.1"):
		info.OS = "Windows 7"
	case strings.Contains(lower, "windows"):
		info.OS = "Windows"
	case strings.Contains(lower, "mac os x"):
		info.OS = "macOS"
		if strings.Contains(lower, "iphone") {
			info.OS = "iOS"
			info.Device = "Mobile"
		} else if strings.Contains(lower, "ipad") {
			info.OS = "iPadOS"
			info.Device = "Tablet"
		}
	case strings.Contains(lower, "android"):
		info.OS = "Android"
		info.Device = "Mobile"
		if strings.Contains(lower, "tablet") || strings.Contains(lower, "ipad") {
			info.Device = "Tablet"
		}
	case strings.Contains(lower, "iphone"):
		info.OS = "iOS"
		info.Device = "Mobile"
	case strings.Contains(lower, "ipad"):
		info.OS = "iPadOS"
		info.Device = "Tablet"
	case strings.Contains(lower, "linux"):
		info.OS = "Linux"
	case strings.Contains(lower, "cros"):
		info.OS = "ChromeOS"
	default:
		info.OS = "Unknown"
	}

	// --- 浏览器 ---
	switch {
	case strings.Contains(lower, "edg/"):
		info.Browser = "Edge"
		info.Browser += extractVersion(ua, "Edg/")
	case strings.Contains(lower, "chrome/") && !strings.Contains(lower, "edg/"):
		info.Browser = "Chrome"
		info.Browser += extractVersion(ua, "Chrome/")
	case strings.Contains(lower, "firefox/"):
		info.Browser = "Firefox"
		info.Browser += extractVersion(ua, "Firefox/")
	case strings.Contains(lower, "safari/") && !strings.Contains(lower, "chrome/"):
		info.Browser = "Safari"
		info.Browser += extractVersion(ua, "Version/")
	default:
		info.Browser = "Unknown"
	}

	return info
}

// extractVersion 从 UA 中提取主版本号
func extractVersion(ua, prefix string) string {
	idx := strings.Index(ua, prefix)
	if idx == -1 {
		return ""
	}
	rest := ua[idx+len(prefix):]
	dot := strings.Index(rest, ".")
	if dot == -1 {
		// 无点号，取到空格或结尾
		sp := strings.Index(rest, " ")
		if sp > 0 {
			return " " + rest[:sp]
		}
		return ""
	}
	return " " + rest[:dot]
}
