package main

import (
	"encoding/base64"
	"fmt"

	"github.com/ipfs/go-cid"
	"github.com/minio/blake2b-simd"
	"github.com/urfave/cli/v2"

	"github.com/filecoin-project/lotus/chain/types"
	lcli "github.com/filecoin-project/lotus/cli"
)

var blockmsgidCmd = &cli.Command{
	Name:      "block-message-id",
	Aliases:   []string{"blockmsgid"},
	Usage:     "Print a block's pubsub message ID",
	ArgsUsage: "<blockCid> ...",
	Action: func(cctx *cli.Context) error {
		api, closer, err := lcli.GetFullNodeAPI(cctx)
		if err != nil {
			return err
		}

		defer closer()
		ctx := lcli.ReqContext(cctx)

		for _, arg := range cctx.Args().Slice() {
			blkcid, err := cid.Decode(arg)
			if err != nil {
				return fmt.Errorf("error decoding block cid: %w", err)
			}

			blkhdr, err := api.ChainGetBlock(ctx, blkcid)
			if err != nil {
				return fmt.Errorf("error retrieving block header: %w", err)
			}

			blkmsgs, err := api.ChainGetBlockMessages(ctx, blkcid)
			if err != nil {
				return fmt.Errorf("error retrieving block messages: %w", err)
			}

			blkmsg := &types.BlockMsg{
				Header: blkhdr,
			}

			for _, m := range blkmsgs.BlsMessages {
				blkmsg.BlsMessages = append(blkmsg.BlsMessages, m.Cid())
			}

			for _, m := range blkmsgs.SecpkMessages {
				blkmsg.SecpkMessages = append(blkmsg.SecpkMessages, m.Cid())
			}

			bytes, err := blkmsg.Serialize()
			if err != nil {
				return fmt.Errorf("error serializing BlockMsg: %w", err)
			}

			msgId := blake2b.Sum256(bytes)
			msgId64 := base64.StdEncoding.EncodeToString(msgId[:])

			fmt.Println(msgId64)
		}

		return nil
	},
}
