package cmd

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/spf13/cobra"

	"github.com/tidbcloud/AgentTeam/desktop/internal/daemoncontrol"
)

var desktopDeepLinkCmd = &cobra.Command{
	Use:          "desktop-deep-link",
	Hidden:       true,
	Short:        "Consume a desktop deep link after daemon readiness",
	SilenceUsage: true,
	Args:         cobra.NoArgs,
	RunE:         runDesktopDeepLink,
}

var exchangeMachineConnectTokenForDesktopDeepLink = exchangeMachineConnectToken
var desktopDeepLinkInput io.Reader = os.Stdin

const maxDesktopDeepLinkBytes = 16 * 1024

func runDesktopDeepLink(_ *cobra.Command, args []string) error {
	status := daemonStatus()
	if !status.Running ||
		!status.Healthy ||
		status.DesktopAPIVersion != daemoncontrol.DesktopAPIVersion ||
		strings.TrimSpace(status.BaseURL) == "" {
		return fmt.Errorf("verified daemon is not ready")
	}
	if len(args) != 0 {
		return fmt.Errorf("desktop deep link must be provided on stdin")
	}

	input, err := io.ReadAll(io.LimitReader(desktopDeepLinkInput, maxDesktopDeepLinkBytes+1))
	if err != nil || len(input) == 0 || len(input) > maxDesktopDeepLinkBytes {
		return fmt.Errorf("invalid desktop deep link input")
	}
	token, serverURL, err := parseConnectURL(string(input))
	if err != nil {
		return fmt.Errorf("invalid desktop deep link")
	}
	result, err := exchangeMachineConnectTokenForDesktopDeepLink(serverURL, token)
	if err != nil {
		return fmt.Errorf("desktop deep-link token exchange failed")
	}
	op, err := getOperator()
	if err != nil {
		return fmt.Errorf("desktop deep-link daemon access failed")
	}
	if _, err := upsertAgentTeamAuth(op.Servers(), *result); err != nil {
		return fmt.Errorf("desktop deep-link profile update failed")
	}
	return nil
}
