package crawl

import (
	"fmt"
	"time"

	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/p2p/discover"
	"github.com/ethereum/go-ethereum/p2p/dnsdisc"
	"github.com/ethereum/go-ethereum/p2p/enode"
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"

	"github.com/0xPolygon/polygon-cli/p2p"
)

type (
	crawlParams struct {
		Bootnodes            string
		DiscoveryDNS         string
		Timeout              string
		timeout              time.Duration
		Threads              int
		NetworkID            uint64
		NodesFile            string
		Database             string
		RevalidationInterval string
		OnlyURLs             bool

		revalidationInterval time.Duration
	}
)

var (
	inputCrawlParams crawlParams
)

// crawlCmd represents the crawl command. This is responsible for crawling the
// devp2p layer and generating a nodes json file with peers.
var CrawlCmd = &cobra.Command{
	Use:   "crawl [nodes file]",
	Short: "Crawl a network on the devp2p layer and generate a nodes JSON file.",
	Long:  "If no nodes.json file exists, it will be created.",
	Args:  cobra.MinimumNArgs(1),
	PreRunE: func(cmd *cobra.Command, args []string) (err error) {
		inputCrawlParams.NodesFile = args[0]

		inputCrawlParams.timeout, err = time.ParseDuration(inputCrawlParams.Timeout)
		if err != nil {
			return err
		}

		inputCrawlParams.revalidationInterval, err = time.ParseDuration(inputCrawlParams.RevalidationInterval)
		if err != nil {
			return err
		}

		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		// Discovery DNS mode
		if inputCrawlParams.DiscoveryDNS != "" {
			dnsclient := dnsdisc.NewClient(dnsdisc.Config{})
			tree, err := dnsclient.SyncTree(inputCrawlParams.DiscoveryDNS)
			if err != nil {
				return err
			}
			return p2p.WriteDNSTreeNodes(inputCrawlParams.NodesFile, tree)
		}
		// Discover V4/V5 mode
		nodes, err := p2p.ReadNodeSet(inputCrawlParams.NodesFile)
		if err != nil {
			log.Warn().Err(err).Msgf("Creating nodes file %v because it does not exist", inputCrawlParams.NodesFile)
		}

		var cfg discover.Config
		cfg.PrivateKey, _ = crypto.GenerateKey()
		cfg.Bootnodes, err = p2p.ParseBootnodes(inputCrawlParams.Bootnodes)
		if err != nil {
			return fmt.Errorf("unable to parse bootnodes: %w", err)
		}

		db, err := enode.OpenDB(inputCrawlParams.Database)
		if err != nil {
			return err
		}

		ln := enode.NewLocalNode(db, cfg.PrivateKey)
		socket, err := p2p.Listen(ln)
		if err != nil {
			return err
		}

		disc, err := discover.ListenV4(socket, ln, cfg)
		if err != nil {
			return err
		}
		defer disc.Close()

		c := newCrawler(nodes, disc, disc.RandomNodes())
		c.revalidateInterval = inputCrawlParams.revalidationInterval

		log.Info().Msg("Starting crawl")

		output := c.run(inputCrawlParams.timeout, inputCrawlParams.Threads)

		if inputCrawlParams.OnlyURLs {
			return p2p.WriteURLs(inputCrawlParams.NodesFile, output)
		}

		return p2p.WriteNodeSet(inputCrawlParams.NodesFile, output, false)

	},
}

func init() {
	f := CrawlCmd.Flags()
	f.StringVarP(&inputCrawlParams.Bootnodes, "bootnodes", "b", "",
		`comma separated nodes used for bootstrapping. At least one bootnode is
required, so other nodes in the network can discover each other`)
	f.StringVarP(&inputCrawlParams.DiscoveryDNS, "discovery-dns", "", "", "enable EIP-1459, DNS Discovery to recover node list from given ENRTree")
	CrawlCmd.MarkFlagsMutuallyExclusive("bootnodes", "discovery-dns")
	f.StringVarP(&inputCrawlParams.Timeout, "timeout", "t", "30m0s", "time limit for the crawl")
	f.IntVarP(&inputCrawlParams.Threads, "parallel", "p", 16, "how many parallel discoveries to attempt")
	f.Uint64VarP(&inputCrawlParams.NetworkID, "network-id", "n", 0, "filter discovered nodes by this network ID")
	f.StringVarP(&inputCrawlParams.Database, "database", "d", "", "node database for updating and storing client information")
	f.StringVarP(&inputCrawlParams.RevalidationInterval, "revalidation-interval", "r", "10m", "time before retrying to connect to a failed peer")
	f.BoolVarP(&inputCrawlParams.OnlyURLs, "only-urls", "u", true, "only writes enode URLs to output")
}
