//go:build ignore
// +build ignore

package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
	"regexp"
	"strings"
	"text/template"
)

var packageTemplate = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT.
package bitfinex

var localSymbolMap = {{ printf "%#v" .LocalSymbols }}
var globalSymbolMap = {{ printf "%#v" .GlobalSymbols }}
var globalCurrencyMap = {{ printf "%#v" .GlobalCurrencies }}
var localCurrencyMap = {{ printf "%#v" .LocalCurrencies }}
`))

func main() {
	const apiBaseUrl = "https://api-pub.bitfinex.com/v2"

	resp, err := http.Get(apiBaseUrl + "/conf/pub:map:currency:sym")
	if err != nil {
		log.Fatal(err)
	}

	defer resp.Body.Close()

	var r [][][]string
	if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
		log.Fatal(err)
	}

	var data = struct {
		LocalSymbols     map[string]string
		GlobalSymbols    map[string]string
		LocalCurrencies  map[string]string
		GlobalCurrencies map[string]string
	}{
		LocalSymbols: map[string]string{
			"UST": "USDT",
			"USE": "USDT",
			"USS": "USDT",
			"UDC": "USDC",
			"TSD": "TUSD",
			"WBT": "WBTC",
		},
		GlobalSymbols: map[string]string{
			"USDT": "UST",
			"USDC": "UDC",
			"TUSD": "TSD",
			"WBTC": "WBT",
		},
		LocalCurrencies:  map[string]string{},
		GlobalCurrencies: map[string]string{},
	}

	for _, pair := range r[0] {
		// skip all symbols that contains TEST
		if strings.Contains(pair[0], "TEST") || strings.Contains(pair[1], "TEST") {
			continue
		}

		local := strings.ToUpper(pair[0])
		global := strings.ToUpper(pair[1])
		data.LocalCurrencies[local] = global
	}

	resp, err = http.Get(apiBaseUrl + "/conf/pub:info:pair")
	if err != nil {
		log.Fatal(err)
	}

	defer resp.Body.Close()

	var pairList [][][]json.RawMessage
	if err := json.NewDecoder(resp.Body).Decode(&pairList); err != nil {
		log.Fatal(err)
	}

	var patchUST = regexp.MustCompile(`UST$`)
	for _, pair := range pairList[0] {
		var localSymbol string
		var globalSymbol string
		var config []any

		_ = json.Unmarshal(pair[0], &localSymbol)
		_ = json.Unmarshal(pair[1], &config)

		// skip all symbols that contains TEST
		if strings.Contains(localSymbol, "TEST") {
			continue
		}

		ss := strings.Split(localSymbol, ":")
		if len(ss) > 1 {
			a := ss[0]
			b := ss[1]
			if v, ok := data.LocalCurrencies[ss[0]]; ok {
				a = v
			}
			if v, ok := data.LocalCurrencies[ss[1]]; ok {
				b = v
			}
			globalSymbol = a + b
		} else {
			globalSymbol = patchUST.ReplaceAllString(localSymbol, "USDT")
		}

		log.Printf("%s: %+v", localSymbol, config)
		log.Printf("%s -> %s", localSymbol, globalSymbol)

		data.LocalSymbols[localSymbol] = globalSymbol
		data.GlobalSymbols[globalSymbol] = localSymbol
	}

	f, err := os.Create("symbols.go")
	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()

	err = packageTemplate.Execute(f, data)
	if err != nil {
		log.Fatal(err)
	}
}
