package reborn

import (
	"fmt"
	"math/rand"
	"os"
	"time"

	ctrl "github.com/FloatTech/zbpctrl"
	"github.com/FloatTech/zbputils/control"
	"github.com/bytedance/sonic"

	wr "github.com/mroth/weightedrand"
	"github.com/sirupsen/logrus"
	zero "github.com/wdvxdr1123/ZeroBot"
	"github.com/wdvxdr1123/ZeroBot/extension/rate"

	"github.com/wdvxdr1123/ZeroBot/message"
)

var (
	areac     *wr.Chooser
	gender, _ = wr.NewChooser(
		wr.Choice{Item: "ç”·å­©å­�", Weight: 33707},
		wr.Choice{Item: "å¥³å­©å­�", Weight: 39292},
		wr.Choice{Item: "é›Œé›„å�Œä½“", Weight: 1001},
		wr.Choice{Item: "çŒ«çŒ«!", Weight: 10000},
		wr.Choice{Item: "ç‹—ç‹—!", Weight: 10000},
		wr.Choice{Item: "ðŸ�‰~", Weight: 3000},
		wr.Choice{Item: "é¾™çŒ«~", Weight: 3000},
	)
	rebornTimerManager = rate.NewManager[int64](time.Minute*2, 8)
	engine             = control.Register("reborn", &ctrl.Options[*zero.Ctx]{
		DisableOnDefault:  false,
		Help:              "reborn - refer to reborn to another nation.",
		PrivateDataFolder: "reborn",
	})
)

type ratego []struct {
	Name   string  `json:"name"`
	Weight float64 `json:"weight"`
}

func init() {
	go func() {
		datapath := engine.DataFolder()
		jsonfile := datapath + "ratego.json"
		area := make(ratego, 226)
		err := load(&area, jsonfile)
		if err != nil {
			panic(err)
		}
		choices := make([]wr.Choice, len(area))
		for i, a := range area {
			choices[i].Item = a.Name
			choices[i].Weight = uint(a.Weight * 1e9)
		}
		areac, err = wr.NewChooser(choices...)
		if err != nil {
			panic(err)
		}
		logrus.Printf("[Reborn]è¯»å�–%dä¸ªå›½å®¶/åœ°åŒº", len(area))
	}()
	engine.OnFullMatchGroup([]string{"reborn", "æˆ‘è¦�é‡�ç”Ÿ", "æˆ‘è¦�é‡�å¼€"}).SetBlock(true).
		Handle(func(ctx *zero.Ctx) {
			if !rebornTimerManager.Load(ctx.Event.GroupID).Acquire() {
				ctx.SendChain(message.Reply(ctx.Event.MessageID), message.Text("å¤ªå¿«äº†å“¦ï¼Œéº»çƒ¦æ…¢ä¸€ç‚¹~"))
				return
			}
			if rand.Int31() > 1<<27 {
				ctx.SendChain(message.At(ctx.Event.UserID), message.Text(fmt.Sprintf("æŠ•èƒŽæˆ�åŠŸï¼�\næ‚¨å‡ºç”Ÿåœ¨ %s, æ˜¯ %sã€‚", randcoun(), randgen())))
			} else {
				ctx.SendChain(message.At(ctx.Event.UserID), message.Text("æŠ•èƒŽå¤±è´¥ï¼�\næ‚¨æ²¡èƒ½æ´»åˆ°å‡ºç”Ÿï¼Œç¥�æ‚¨ä¸‹æ¬¡å¥½è¿�ï¼�"))
			}
		})
}

// load åŠ è½½rateæ•°æ�®
func load(area *ratego, jsonfile string) error {
	data, err := os.ReadFile(jsonfile)
	if err != nil {
		return err
	}
	return sonic.Unmarshal(data, area)
}

func randcoun() string {
	return areac.Pick().(string)
}

func randgen() string {
	return gender.Pick().(string)
}
