package menu

import (
	"context"
	"errors"
	"fmt"
	"io"

	"frpc-tool/internal/autostart"
	"frpc-tool/internal/config"
	"frpc-tool/internal/install"
	"frpc-tool/internal/runner"
	"frpc-tool/internal/util"
)

func HandleDeployConfig(ctx context.Context, env util.Environment, source string, stdout, stderr io.Writer) error {
	manager := config.NewManager(env)
	path, err := manager.Deploy(ctx, source)
	if err != nil {
		fmt.Fprintf(stderr, "部署配置失败：%v\n", err)
		return err
	}
	fmt.Fprintf(stdout, "配置已写入：%s\n", path)
	return nil
}

func HandleStart(ctx context.Context, env util.Environment, stdout, stderr io.Writer) error {
	r := runner.New(env)
	mode, err := r.Start(ctx)
	if err != nil {
		fmt.Fprintf(stderr, "启动失败：%v\n", err)
		return err
	}
	fmt.Fprintf(stdout, "frpc 已启动（模式：%s）\n", mode)
	return nil
}

func HandleStop(ctx context.Context, env util.Environment, stdout, stderr io.Writer) error {
	r := runner.New(env)
	mode, err := r.Stop(ctx)
	if err != nil {
		fmt.Fprintf(stderr, "停止失败：%v\n", err)
		return err
	}
	fmt.Fprintf(stdout, "frpc 已停止（模式：%s）\n", mode)
	return nil
}

func HandleRestart(ctx context.Context, env util.Environment, stdout, stderr io.Writer) error {
	r := runner.New(env)
	mode, err := r.Restart(ctx)
	if err != nil {
		fmt.Fprintf(stderr, "重启失败：%v\n", err)
		return err
	}
	fmt.Fprintf(stdout, "frpc 已重启（模式：%s）\n", mode)
	return nil
}

func HandleStatus(ctx context.Context, env util.Environment, stdout, stderr io.Writer) error {
	r := runner.New(env)
	status, err := r.Status(ctx)
	if err != nil {
		fmt.Fprintf(stderr, "查询状态失败：%v\n", err)
		return err
	}
	fmt.Fprintln(stdout, status)
	return nil
}

func HandleInstall(env util.Environment, stdout, stderr io.Writer) error {
	created, err := install.EnsureFrpcBinary(env)
	if err != nil {
		if errors.Is(err, install.ErrUnsupportedPlatform) {
			fmt.Fprintf(stderr, "当前仅支持在 macOS arm64 上安装 frpc。\n")
		} else {
			fmt.Fprintf(stderr, "安装 frpc 失败：%v\n", err)
		}
		return err
	}

	if !created {
		fmt.Fprintf(stdout, "检测到已存在 frpc，可执行路径：%s\n", env.BinaryPath)
		return nil
	}

	fmt.Fprintf(stdout, "frpc 已安装到：%s\n", env.BinaryPath)
	return nil
}

func HandleEnableService(ctx context.Context, env util.Environment, stdout, stderr io.Writer) error {
	manager := autostart.NewManager(env)
	if manager == nil {
		fmt.Fprintln(stderr, "当前系统暂不支持自动安装自启服务，请手动配置。")
		return fmt.Errorf("不支持的自启平台")
	}
	if err := manager.Enable(ctx); err != nil {
		fmt.Fprintf(stderr, "安装自启服务失败：%v\n", err)
		return err
	}
	fmt.Fprintf(stdout, "自启服务已安装（类型：%s）\n", manager.Kind())
	return nil
}

func HandleDisableService(ctx context.Context, env util.Environment, stdout, stderr io.Writer) error {
	manager := autostart.NewManager(env)
	if manager == nil {
		fmt.Fprintln(stderr, "当前系统未提供自启服务管理。")
		return fmt.Errorf("不支持的自启平台")
	}
	if err := manager.Disable(ctx); err != nil {
		fmt.Fprintf(stderr, "卸载自启服务失败：%v\n", err)
		return err
	}
	fmt.Fprintf(stdout, "自启服务已卸载（类型：%s）\n", manager.Kind())
	return nil
}
