package menu

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

	"index-go/config"
	"index-go/daemon"
	"index-go/service"
)

// ServiceMenu 系统守护管理菜单
type ServiceMenu struct {
	serviceManager service.ServiceManager
	detector       *service.PlatformDetector
	scanner        *bufio.Scanner
	cfg            *config.Config
}

func NewServiceMenu(cfg *config.Config) *ServiceMenu {
	return &ServiceMenu{
		scanner: bufio.NewScanner(os.Stdin),
		cfg:     cfg,
	}
}

func (m *ServiceMenu) Show() error {
	if err := m.initializeServiceManager(); err != nil {
		return fmt.Errorf("初始化服务管理器失败: %v", err)
	}

	for {
		clearScreen()
		fmt.Println("系统守护管理")
		fmt.Println("============================================================")
		fmt.Println(m.detector.FormatPlatformInfo())
		fmt.Println("============================================================")
		fmt.Println("当前状态:")
		fmt.Println(service.FormatServiceStatus(m.serviceManager.GetServiceStatus()))
		fmt.Println("============================================================")
		fmt.Println("请选择操作:")
		fmt.Println("  1. 启用自启守护")
		fmt.Println("  2. 禁用自启守护")
		fmt.Println("  3. 返回主菜单")
		fmt.Print("请输入选项 [1-3]: ")

		if !m.scanner.Scan() {
			return fmt.Errorf("读取用户输入失败")
		}

		switch strings.TrimSpace(m.scanner.Text()) {
		case "1":
			if err := m.enableServer(); err != nil {
				fmt.Printf("❌ %v\n", err)
			} else {
				fmt.Println("✅ 系统守护已启用")
			}
			waitEnter()
		case "2":
			if err := m.disableServer(); err != nil {
				fmt.Printf("❌ %v\n", err)
			} else {
				fmt.Println("✅ 系统守护已禁用")
			}
			waitEnter()
		case "3":
			return nil
		default:
			fmt.Println("❌ 无效选项")
			waitEnter()
		}
	}
}

func (m *ServiceMenu) initializeServiceManager() error {
	var err error
	m.detector = service.NewPlatformDetector()
	m.detector.Detect()

	m.serviceManager, err = service.CreateServiceManager()
	if err != nil {
		return err
	}
	return nil
}

func (m *ServiceMenu) enableServer() error {
	if err := daemon.EnsureStopped(); err != nil {
		fmt.Printf("⚠️ 停止后台服务失败: %v\n", err)
	}

	if !m.serviceManager.IsServiceInstalled() {
		if err := m.serviceManager.InstallService(); err != nil {
			return fmt.Errorf("安装守护失败: %w", err)
		}
	}

	if err := m.serviceManager.EnableAutostart(); err != nil {
		return fmt.Errorf("启用自启失败: %w", err)
	}

	if err := m.serviceManager.StartService(); err != nil {
		return fmt.Errorf("启动守护失败: %w", err)
	}
	return nil
}

func (m *ServiceMenu) disableServer() error {
	if m.serviceManager.IsServiceInstalled() {
		_ = m.serviceManager.StopService()
		if err := m.serviceManager.DisableAutostart(); err != nil {
			return fmt.Errorf("禁用自启失败: %w", err)
		}
		if err := m.serviceManager.UninstallService(); err != nil {
			return fmt.Errorf("卸载守护失败: %w", err)
		}
	}

	if m.cfg != nil {
		if err := daemon.Start(m.cfg); err != nil {
			fmt.Printf("⚠️ 启动后台服务失败: %v\n", err)
		} else {
			fmt.Println("✅ 已切换回后台服务模式")
		}
	}
	return nil
}

func clearScreen() {
	var cmd *exec.Cmd
	if runtime.GOOS == "windows" {
		cmd = exec.Command("cmd", "/c", "cls")
	} else {
		cmd = exec.Command("clear")
	}
	cmd.Stdout = os.Stdout
	cmd.Run()
}

func waitEnter() {
	fmt.Print("按回车键继续...")
	bufio.NewReader(os.Stdin).ReadBytes('\n')
}
