package cmd

import (
	"encoding/json"
	"fmt"
	"strconv"

	"github.com/spf13/cobra"

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

var desktopProcessIdentityCmd = &cobra.Command{
	Use:          "desktop-process-identity [pid]",
	Hidden:       true,
	SilenceUsage: true,
	Args:         cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		pid, err := strconv.Atoi(args[0])
		if err != nil || pid <= 0 {
			return fmt.Errorf("invalid process id")
		}
		process, ok := proc.ProcessByPID(pid)
		if !ok || process.StartedAt.IsZero() {
			return fmt.Errorf("process identity is unavailable")
		}
		return json.NewEncoder(cmd.OutOrStdout()).Encode(daemoncontrol.ProcessIdentity{
			PID:       process.PID,
			StartedAt: process.StartedAt,
			StartID:   process.StartID,
		})
	},
}

var desktopReceiptVerifyCmd = &cobra.Command{
	Use:          "desktop-receipt-verify",
	Hidden:       true,
	SilenceUsage: true,
	Args:         cobra.NoArgs,
	RunE: func(*cobra.Command, []string) error {
		err := daemoncontrol.DefaultReceiptStore().VerifySecurity()
		if err != nil {
			return fmt.Errorf("daemon receipt verification failed: %w", err)
		}
		return nil
	},
}
