//go:build ignore
// +build ignore

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"text/template"
	"time"

	api "github.com/c9s/bbgo/pkg/exchange/coinbase/api/v1"
)

var packageTemplate = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT.
// generated on {{ .GenerateTime }}
package coinbase

var symbolMap = map[string]string{
{{- range $k, $v := .Data }}
	{{ printf "%q" $k }}: {{ printf "%q" $v }},
{{- end }}
}

var invSymbolMap map[string]string

func init() {
	invSymbolMap = make(map[string]string, len(symbolMap))
	for k, v := range symbolMap {
		invSymbolMap[v] = k
	}
}

func toLocalSymbol(symbol string) string {
	s, ok := symbolMap[symbol]
	if ok {
		return s
	}

	return symbol
}

func toGlobalSymbol(symbol string) string {
	s, ok := invSymbolMap[symbol]
	if ok {
		return s
	}

	return symbol
}
`))

type Market struct {
	ID string `json:"id"`
}

type ApiResponse []Market

type TemplateData struct {
	Data         map[string]string
	GenerateTime string
}

func main() {

	const apiUrl = api.ProductionAPIURL + "/products"

	resp, err := http.Get(apiUrl)
	if err != nil {
		log.Fatal(err)
	}

	defer resp.Body.Close()

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

	var data = map[string]string{}
	for _, m := range r {
		key := strings.ReplaceAll(strings.ToUpper(strings.TrimSpace(m.ID)), "-", "")
		data[key] = m.ID
	}

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

	defer f.Close()

	loc, _ := time.LoadLocation("UTC")
	err = packageTemplate.Execute(f, TemplateData{Data: data, GenerateTime: fmt.Sprintf("%s", time.Now().UTC().In(loc))})
	if err != nil {
		log.Fatal(err)
	}
}
