package main

import (
	"fmt"

	"github.com/ipfs/go-cid"

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

var syncCmd = &cli.Command{
	Name:  "sync",
	Usage: "tools for diagnosing sync issues",
	Flags: []cli.Flag{},
	Subcommands: []*cli.Command{
		syncValidateCmd,
	},
}

var syncValidateCmd = &cli.Command{
	Name:  "validate",
	Usage: "checks whether a provided tipset is valid",
	Action: func(cctx *cli.Context) error {
		api, closer, err := lcli.GetFullNodeAPI(cctx)
		if err != nil {
			return err
		}

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

		if cctx.Args().Len() < 1 {
			fmt.Println("usage: <blockCid1> <blockCid2>...")
			fmt.Println("At least one block cid must be provided")
			return nil
		}

		args := cctx.Args().Slice()

		var tscids []cid.Cid
		for _, s := range args {
			c, err := cid.Decode(s)
			if err != nil {
				return fmt.Errorf("block cid was invalid: %s", err)
			}
			tscids = append(tscids, c)
		}

		tsk := types.NewTipSetKey(tscids...)

		valid, err := api.SyncValidateTipset(ctx, tsk)
		if err != nil {
			fmt.Println("Tipset is invalid: ", err)
		}

		if valid {
			fmt.Println("Tipset is valid")
		}

		return nil
	},
}