package main

import (
	"context"
	"fmt"
	"time"

	"github.com/spf13/cobra"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	pb "git.wntrmute.dev/kyle/mc-proxy/gen/mc_proxy/v1"
	"git.wntrmute.dev/kyle/mc-proxy/internal/config"
)

func statusCmd() *cobra.Command {
	var configPath string

	cmd := &cobra.Command{
		Use:   "status",
		Short: "Query a running instance's health and status",
		RunE: func(cmd *cobra.Command, args []string) error {
			cfg, err := config.Load(configPath)
			if err != nil {
				return err
			}

			if cfg.GRPC.Addr == "" {
				return fmt.Errorf("gRPC admin API is not configured (grpc.addr is empty)")
			}

			conn, err := dialGRPC(cfg.GRPC)
			if err != nil {
				return fmt.Errorf("connecting to gRPC API: %w", err)
			}
			defer conn.Close()

			client := pb.NewProxyAdminServiceClient(conn)

			ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()

			resp, err := client.GetStatus(ctx, &pb.GetStatusRequest{})
			if err != nil {
				return fmt.Errorf("getting status: %w", err)
			}

			fmt.Printf("mc-proxy %s\n", resp.Version)
			if resp.StartedAt != nil {
				uptime := time.Since(resp.StartedAt.AsTime()).Truncate(time.Second)
				fmt.Printf("uptime:      %s\n", uptime)
			}
			fmt.Printf("connections: %d\n", resp.TotalConnections)
			fmt.Println()

			for _, ls := range resp.Listeners {
				fmt.Printf("  %s  routes=%d  active=%d\n", ls.Addr, ls.RouteCount, ls.ActiveConnections)
			}

			return nil
		},
	}

	cmd.Flags().StringVarP(&configPath, "config", "c", "mc-proxy.toml", "path to configuration file")

	return cmd
}

func dialGRPC(cfg config.GRPC) (*grpc.ClientConn, error) {
	return grpc.NewClient("unix://"+cfg.SocketPath(),
		grpc.WithTransportCredentials(insecure.NewCredentials()))
}
