package service

import (
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"strings"
)

// OSType 操作系统类型
type OSType string

const (
	OS_Darwin  OSType = "darwin"
	OS_Linux   OSType = "linux"
	OS_Windows OSType = "windows"
	OS_Unknown OSType = "unknown"
)

// ServiceManagerType 服务管理器类型
type ServiceManagerType string

const (
	ServiceMgr_Launchd  ServiceManagerType = "launchd"
	ServiceMgr_Systemd  ServiceManagerType = "systemd"
	ServiceMgr_SysVInit ServiceManagerType = "sysvinit"
	ServiceMgr_Unknown  ServiceManagerType = "unknown"
)

// PlatformInfo 平台信息
type PlatformInfo struct {
	OSType            OSType             `json:"os_type"`
	Platform          string             `json:"platform"`
	Version           string             `json:"version"`
	Architecture      string             `json:"architecture"`
	ServiceMgr        ServiceManagerType `json:"service_mgr"`
	ServiceMgrPath    string             `json:"service_mgr_path"`
	RecommendedType   string             `json:"recommended_type"`
	UserLevel         bool               `json:"user_level"`
	SupportsAutostart bool               `json:"supports_autostart"`
}

// PlatformDetector 平台检测器
type PlatformDetector struct {
	info *PlatformInfo
}

// NewPlatformDetector 创建新的平台检测器
func NewPlatformDetector() *PlatformDetector {
	return &PlatformDetector{
		info: &PlatformInfo{},
	}
}

// Detect 检测平台信息
func (d *PlatformDetector) Detect() *PlatformInfo {
	d.detectOSType()
	d.detectPlatformInfo()
	d.detectServiceManager()
	d.selectBestImplementation()
	d.detectAutostartSupport()

	return d.info
}

// detectOSType 检测操作系统类型
func (d *PlatformDetector) detectOSType() {
	switch runtime.GOOS {
	case "darwin":
		d.info.OSType = OS_Darwin
		d.info.Platform = "macOS"
	case "linux":
		d.info.OSType = OS_Linux
		d.info.Platform = "Linux"
	case "windows":
		d.info.OSType = OS_Windows
		d.info.Platform = "Windows"
	default:
		d.info.OSType = OS_Unknown
		d.info.Platform = "Unknown"
	}
}

// detectPlatformInfo 检测具体平台信息
func (d *PlatformDetector) detectPlatformInfo() {
	// 获取系统版本
	if d.info.OSType == OS_Darwin {
		d.info.Version = d.getDarwinVersion()
	} else if d.info.OSType == OS_Linux {
		d.info.Version = d.getLinuxVersion()
	}

	// 获取架构信息
	d.info.Architecture = runtime.GOARCH

	// 默认推荐用户级服务
	d.info.UserLevel = true
}

// getDarwinVersion 获取macOS版本
func (d *PlatformDetector) getDarwinVersion() string {
	if output, err := exec.Command("sw_vers", "-productVersion").Output(); err == nil {
		return strings.TrimSpace(string(output))
	}
	return "Unknown"
}

// getLinuxVersion 获取Linux版本
func (d *PlatformDetector) getLinuxVersion() string {
	// 尝试从 /etc/os-release 读取
	if content, err := os.ReadFile("/etc/os-release"); err == nil {
		lines := strings.Split(string(content), "\n")
		for _, line := range lines {
			if strings.HasPrefix(line, "PRETTY_NAME=") {
				return strings.Trim(strings.Split(line, "=")[1], `"`)
			}
		}
	}

	// 备用方法
	if output, err := exec.Command("uname", "-r").Output(); err == nil {
		return strings.TrimSpace(string(output))
	}

	return "Unknown"
}

// detectServiceManager 检测可用的服务管理工具
func (d *PlatformDetector) detectServiceManager() {
	switch d.info.OSType {
	case OS_Darwin:
		d.info.ServiceMgr = ServiceMgr_Launchd
		d.info.ServiceMgrPath = "/bin/launchd"

	case OS_Linux:
		// 检测systemd
		if _, err := exec.LookPath("systemctl"); err == nil {
			d.info.ServiceMgr = ServiceMgr_Systemd
			d.info.ServiceMgrPath = "/bin/systemctl"

			// 检测systemd版本
			if output, err := exec.Command("systemctl", "--version").Output(); err == nil {
				lines := strings.Split(string(output), "\n")
				if len(lines) > 0 {
					d.info.Version += " (systemd " + strings.Fields(lines[0])[1] + ")"
				}
			}
		} else if _, err := exec.LookPath("service"); err == nil {
			d.info.ServiceMgr = ServiceMgr_SysVInit
			d.info.ServiceMgrPath = "/sbin/service"
		} else {
			d.info.ServiceMgr = ServiceMgr_Unknown
		}

	default:
		d.info.ServiceMgr = ServiceMgr_Unknown
	}
}

// selectBestImplementation 选择最佳实现方案
func (d *PlatformDetector) selectBestImplementation() {
	switch d.info.OSType {
	case OS_Darwin:
		d.info.RecommendedType = "LaunchAgent (用户级服务)"
		d.info.UserLevel = true

	case OS_Linux:
		if d.info.ServiceMgr == ServiceMgr_Systemd {
			// 检测是否有权限创建用户级服务
			if d.supportsUserLevelSystemd() {
				d.info.RecommendedType = "systemd 用户级服务"
				d.info.UserLevel = true
			} else {
				d.info.RecommendedType = "systemd 系统级服务"
				d.info.UserLevel = false
			}
		} else if d.info.ServiceMgr == ServiceMgr_SysVInit {
			d.info.RecommendedType = "SysVInit 系统级服务"
			d.info.UserLevel = false
		} else {
			d.info.RecommendedType = "不支持的服务管理器"
		}

	default:
		d.info.RecommendedType = "不支持的操作系统"
	}
}

// supportsUserLevelSystemd 检测是否支持用户级systemd服务
func (d *PlatformDetector) supportsUserLevelSystemd() bool {
	// 检查用户级systemd目录是否存在
	userServiceDir := os.Getenv("HOME") + "/.config/systemd/user"
	if _, err := os.Stat(userServiceDir); err == nil {
		return true
	}

	// 检查systemd --user是否可用
	if _, err := exec.LookPath("systemctl"); err == nil {
		cmd := exec.Command("systemctl", "--user", "--version")
		err := cmd.Run()
		return err == nil
	}

	return false
}

// detectAutostartSupport 检测开机自启支持
func (d *PlatformDetector) detectAutostartSupport() {
	switch d.info.OSType {
	case OS_Darwin:
		d.info.SupportsAutostart = true // LaunchAgent支持开机自启
	case OS_Linux:
		d.info.SupportsAutostart = d.info.ServiceMgr == ServiceMgr_Systemd || d.info.ServiceMgr == ServiceMgr_SysVInit
	default:
		d.info.SupportsAutostart = false
	}
}

// GetPlatformInfo 获取平台信息
func (d *PlatformDetector) GetPlatformInfo() *PlatformInfo {
	if d.info == nil {
		d.Detect()
	}
	return d.info
}

// IsSupported 检测当前平台是否受支持
func (d *PlatformDetector) IsSupported() bool {
	return d.info.OSType == OS_Darwin ||
		(d.info.OSType == OS_Linux && d.info.ServiceMgr != ServiceMgr_Unknown)
}

// GetServiceManagerPath 获取服务管理器路径
func (d *PlatformDetector) GetServiceManagerPath() string {
	return d.info.ServiceMgrPath
}

// GetRecommendedServiceType 获取推荐的服务类型
func (d *PlatformDetector) GetRecommendedServiceType() string {
	return d.info.RecommendedType
}

// IsUserLevelRecommended 是否推荐用户级服务
func (d *PlatformDetector) IsUserLevelRecommended() bool {
	return d.info.UserLevel
}

// FormatPlatformInfo 格式化平台信息显示
func (d *PlatformDetector) FormatPlatformInfo() string {
	if d.info == nil {
		d.Detect()
	}

	var result strings.Builder
	result.WriteString("🖥️ 系统环境检测结果\n")
	result.WriteString("   操作系统: " + d.info.Platform + " " + d.info.Version + "\n")
	result.WriteString("   架构: " + d.info.Architecture + "\n")
	result.WriteString("   服务管理: " + string(d.info.ServiceMgr) + "\n")
	result.WriteString("   推荐方案: " + d.info.RecommendedType + "\n")
	result.WriteString("   用户级: " + fmt.Sprintf("%v", d.info.UserLevel) + "\n")
	result.WriteString("   支持自启: " + fmt.Sprintf("%v", d.info.SupportsAutostart) + "\n")

	return result.String()
}

// FormatSmartSuggestions 格式化智能提示信息
func (d *PlatformDetector) FormatSmartSuggestions() string {
	if d.info == nil {
		d.Detect()
	}

	var result strings.Builder
	result.WriteString("💡 智能建议:\n")

	switch d.info.OSType {
	case OS_Darwin:
		result.WriteString("   🍎 macOS用户提示:\n")
		result.WriteString("   • 建议使用LaunchAgent用户级服务\n")
		result.WriteString("   • 无需管理员权限，安装简单\n")
		result.WriteString("   • 登录用户时自动启动服务\n")
		result.WriteString("   • 服务崩溃会自动重启\n")
		result.WriteString("   • 日志位置: ~/Library/Logs/\n")

	case OS_Linux:
		if d.info.ServiceMgr == ServiceMgr_Systemd {
			if d.info.UserLevel {
				result.WriteString("   🐧 Linux用户提示:\n")
				result.WriteString("   • 检测到systemd，推荐用户级服务\n")
				result.WriteString("   • 无需root权限，安装安全\n")
				result.WriteString("   • 用户登录时自动启动\n")
				result.WriteString("   • 使用systemctl --user管理\n")
				result.WriteString("   • 日志位置: journalctl --user\n")
			} else {
				result.WriteString("   🐧 Linux用户提示:\n")
				result.WriteString("   • 检测到systemd，推荐系统级服务\n")
				result.WriteString("   • 需要root权限安装\n")
				result.WriteString("   • 开机时自动启动\n")
				result.WriteString("   • 使用systemctl管理\n")
				result.WriteString("   • 日志位置: journalctl\n")
			}
		} else if d.info.ServiceMgr == ServiceMgr_SysVInit {
			result.WriteString("   🐧 Linux用户提示:\n")
			result.WriteString("   • 检测到传统SysVInit\n")
			result.WriteString("   • 需要root权限安装\n")
			result.WriteString("   • 使用service命令管理\n")
			result.WriteString("   • 建议升级到支持systemd的系统\n")
		} else {
			result.WriteString("   ❌ 不支持的Linux系统\n")
			result.WriteString("   • 未检测到标准服务管理器\n")
			result.WriteString("   • 建议使用现代Linux发行版\n")
		}

	default:
		result.WriteString("   ❌ 不支持的操作系统\n")
		result.WriteString("   • 仅支持macOS和Linux系统\n")
	}

	return result.String()
}
