package service

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

// ServiceStatus 服务状态
type ServiceStatus struct {
	Platform     string    `json:"platform"`
	ServiceName  string    `json:"service_name"`
	IsInstalled  bool      `json:"is_installed"`
	IsRunning    bool      `json:"is_running"`
	Autostart    bool      `json:"autostart"`
	LastModified time.Time `json:"last_modified"`
	Pid          int       `json:"pid"`
	Uptime       string    `json:"uptime"`
	Status       string    `json:"status"`
	ErrorMsg     string    `json:"error_msg,omitempty"`
}

// ServiceConfig 服务配置
type ServiceConfig struct {
	ServiceName   string            `json:"service_name"`
	DisplayName   string            `json:"display_name"`
	Description   string            `json:"description"`
	Platform      string            `json:"platform"`
	ExecPath      string            `json:"exec_path"`
	Args          []string          `json:"args"`
	WorkingDir    string            `json:"working_directory"`
	LogFile       string            `json:"log_file"`
	ErrorFile     string            `json:"error_file"`
	UserLevel     bool              `json:"user_level"`
	Autostart     bool              `json:"autostart"`
	RestartPolicy string            `json:"restart_policy"`
	Environment   map[string]string `json:"environment"`
}

// ServiceManager 服务管理器接口
type ServiceManager interface {
	// 系统信息
	GetPlatformInfo() *PlatformInfo

	// 核心功能
	InstallService() error
	UninstallService() error
	StartService() error
	StopService() error
	RestartService() error

	// 状态查询
	GetServiceStatus() *ServiceStatus
	IsServiceInstalled() bool
	IsServiceRunning() bool

	// 配置管理
	EnableAutostart() error
	DisableAutostart() error
	IsAutostartEnabled() bool

	// 日志管理
	GetServiceLogs(lines int) ([]string, error)
	FollowLogs() error

	// 配置文件管理
	GetServiceConfig() *ServiceConfig
	UpdateServiceConfig(config *ServiceConfig) error
}

// BaseServiceManager 基础服务管理器
type BaseServiceManager struct {
	detector *PlatformDetector
	config   *ServiceConfig
}

// NewBaseServiceManager 创建基础服务管理器
func NewBaseServiceManager(detector *PlatformDetector) *BaseServiceManager {
	return &BaseServiceManager{
		detector: detector,
		config:   createDefaultServiceConfig(detector),
	}
}

// createDefaultServiceConfig 创建默认服务配置
func createDefaultServiceConfig(detector *PlatformDetector) *ServiceConfig {
	info := detector.GetPlatformInfo()

	// 获取可执行文件路径
	execPath, _ := os.Executable()
	if execPath == "" {
		// 如果无法获取绝对路径，尝试从当前目录获取
		cwd, _ := os.Getwd()
		if cwd != "" {
			execPath = filepath.Join(cwd, "cos-index")
		} else {
			execPath = "./cos-index"
		}
	}

	// 确保路径是绝对路径
	if !filepath.IsAbs(execPath) {
		cwd, _ := os.Getwd()
		if cwd != "" {
			execPath = filepath.Join(cwd, execPath)
		}
	}

	// 获取工作目录
	workingDir, _ := os.Getwd()
	if workingDir == "" {
		workingDir = "/tmp"
	}

	// 设置日志文件路径 - 使用程序运行目录
	logFile := filepath.Join(workingDir, "logs", "cos-index.log")
	errorFile := filepath.Join(workingDir, "logs", "cos-index-error.log")

	return &ServiceConfig{
		ServiceName:   "com.company.cos-index",
		DisplayName:   "COS Index Generator",
		Description:   "腾讯云COS索引生成工具",
		Platform:      string(info.OSType),
		ExecPath:      execPath,
		Args:          []string{"--run"},
		WorkingDir:    workingDir,
		LogFile:       logFile,
		ErrorFile:     errorFile,
		UserLevel:     info.UserLevel,
		Autostart:     true,
		RestartPolicy: "always",
		Environment: map[string]string{
			"GIN_MODE": "release",
		},
	}
}

// GetPlatformInfo 获取平台信息
func (b *BaseServiceManager) GetPlatformInfo() *PlatformInfo {
	return b.detector.GetPlatformInfo()
}

// GetServiceConfig 获取服务配置
func (b *BaseServiceManager) GetServiceConfig() *ServiceConfig {
	return b.config
}

// UpdateServiceConfig 更新服务配置
func (b *BaseServiceManager) UpdateServiceConfig(config *ServiceConfig) error {
	b.config = config
	return nil
}

// ensureLogDirectory 确保日志目录存在
func ensureLogDirectory(logPath string) error {
	logDir := filepath.Dir(logPath)
	return os.MkdirAll(logDir, 0755)
}

// checkExecutablePath 检查可执行文件路径
func checkExecutablePath(path string) error {
	if path == "" {
		return fmt.Errorf("可执行文件路径为空")
	}

	// 如果是相对路径，转换为绝对路径
	if !filepath.IsAbs(path) {
		cwd, err := os.Getwd()
		if err != nil {
			return fmt.Errorf("无法获取当前工作目录: %v", err)
		}
		path = filepath.Join(cwd, path)
	}

	// 检查文件是否存在
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("可执行文件不存在: %s", path)
		}
		return fmt.Errorf("无法访问可执行文件: %v", err)
	}

	return nil
}

// runCommand 运行系统命令
func runCommand(name string, args ...string) (string, error) {
	cmd := exec.Command(name, args...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return string(output), fmt.Errorf("命令执行失败: %s %s: %v", name, strings.Join(args, " "), err)
	}
	return string(output), nil
}

// runCommandWithSudo 使用sudo运行系统命令
func runCommandWithSudo(name string, args ...string) (string, error) {
	fullArgs := append([]string{name}, args...)
	cmd := exec.Command("sudo", fullArgs...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return string(output), fmt.Errorf("sudo命令执行失败: %s %s: %v", name, strings.Join(args, " "), err)
	}
	return string(output), nil
}

// FormatServiceStatus 格式化服务状态显示
func FormatServiceStatus(status *ServiceStatus) string {
	var result strings.Builder
	result.WriteString("📊 当前服务状态\n")
	result.WriteString("============================================================\n")

	// 安装状态
	installStatus := "❌ 未安装"
	if status.IsInstalled {
		installStatus = "✅ 已安装"
	}
	result.WriteString("   服务状态: " + installStatus + "\n")

	// 运行状态
	runStatus := "⏹️ 已停止"
	if status.IsRunning {
		runStatus = "✅ 运行中"
	}
	result.WriteString("   运行状态: " + runStatus + "\n")

	// 自启动状态
	autostartStatus := "❌ 未启用"
	if status.Autostart {
		autostartStatus = "✅ 已启用"
	}
	result.WriteString("   开机自启: " + autostartStatus + "\n")

	// 额外信息
	if status.Pid > 0 {
		result.WriteString(fmt.Sprintf("   进程ID: %d\n", status.Pid))
	}

	if status.Uptime != "" {
		result.WriteString("   运行时长: " + status.Uptime + "\n")
	}

	if !status.LastModified.IsZero() {
		result.WriteString("   最后更新: " + status.LastModified.Format("2006-01-02 15:04:05") + "\n")
	}

	if status.ErrorMsg != "" {
		result.WriteString("   错误信息: " + status.ErrorMsg + "\n")
	}

	result.WriteString("============================================================\n")

	return result.String()
}

// CreateServiceManager 创建服务管理器实例
func CreateServiceManager() (ServiceManager, error) {
	detector := NewPlatformDetector()
	info := detector.Detect()

	if !detector.IsSupported() {
		return nil, fmt.Errorf("当前平台 %s 不受支持", info.Platform)
	}

	switch info.OSType {
	case OS_Darwin:
		return NewDarwinServiceManager(detector), nil
	case OS_Linux:
		if info.ServiceMgr == ServiceMgr_Systemd {
			return NewLinuxServiceManager(detector), nil
		} else if info.ServiceMgr == ServiceMgr_SysVInit {
			return NewLinuxServiceManager(detector), nil
		}
		return nil, fmt.Errorf("Linux系统 %s 不支持的服务管理器: %s", info.Platform, info.ServiceMgr)
	default:
		return nil, fmt.Errorf("不支持的操作系统: %s", info.Platform)
	}
}
