package main

import (
	"flag"
	"fmt"
	"math/big"

	"github.com/deltaswapio/swaprouter/v3/common"
	"github.com/deltaswapio/swaprouter/v3/log"
	"github.com/deltaswapio/swaprouter/v3/mpc"
	"github.com/deltaswapio/swaprouter/v3/params"
	"github.com/deltaswapio/swaprouter/v3/tokens"
	"github.com/deltaswapio/swaprouter/v3/tokens/cardano"
)

var (
	b               = cardano.NewCrossChainBridge()
	paramConfigFile string
	paramChainID    string
	chainID         = big.NewInt(0)
	mpcConfig       *mpc.Config
	paramPubkey     string
)

func main() {
	log.SetLogger(6, false, true)

	initAll()

	addr, err := b.PublicKeyToAddress(paramPubkey)
	if err != nil {
		panic(err)
	}
	fmt.Println(addr)
}

func initAll() {
	initFlags()
	initConfig()
	initBridge()
}

func initConfig() {
	config := params.LoadRouterConfig(paramConfigFile, true, false)
	if config.FastMPC != nil {
		mpcConfig = mpc.InitConfig(config.FastMPC, true)
	} else {
		mpcConfig = mpc.InitConfig(config.MPC, true)
	}
	log.Info("init config finished", "IsFastMPC", mpcConfig.IsFastMPC)
}

func initBridge() {
	cfg := params.GetRouterConfig()
	apiAddrs := cfg.Gateways[chainID.String()]
	if len(apiAddrs) == 0 {
		log.Fatal("gateway not found for chain ID", "chainID", chainID)
	}
	apiAddrsExt := cfg.GatewaysExt[chainID.String()]
	b.SetGatewayConfig(&tokens.GatewayConfig{
		APIAddress:    apiAddrs,
		APIAddressExt: apiAddrsExt,
	})

	b.SetChainConfig(&tokens.ChainConfig{
		BlockChain:    "Cardano",
		ChainID:       chainID.String(),
		Confirmations: 1,
	})

	_ = b.GetChainConfig().CheckConfig()

	b.InitAfterConfig()

	log.Info("init bridge finished")
}

func initFlags() {
	flag.StringVar(&paramConfigFile, "config", "", "config file to init mpc and gateway")
	flag.StringVar(&paramChainID, "chainID", "", "chain id")
	flag.StringVar(&paramPubkey, "pubkey", "", "pubkey")
	flag.Parse()

	if paramChainID != "" {
		cid, err := common.GetBigIntFromStr(paramChainID)
		if err != nil {
			log.Fatal("wrong param chainID", "err", err)
		}
		chainID = cid
	}

	log.Info("init flags finished")
}
