package beatleader

import (
	"compress/gzip"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// fetchPlayerData 函数请求 BeatLeader API，并解析完整的玩家信息
func FetchPlayerData(blID string) (*PlayerData, error) {
	url := fmt.Sprintf("https://api.beatleader.xyz/player/%s?leaderboardContext=general", blID)

	// 创建请求
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}

	// 设置请求头
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0")
	req.Header.Set("Accept", "application/json, text/plain, */*")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
	req.Header.Set("Accept-Encoding", "gzip")
	req.Header.Set("DNT", "1")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Referer", fmt.Sprintf("https://beatleader.xyz/u/%s/scores/date/desc/1", blID))
	req.Header.Set("Sec-Fetch-Dest", "empty")
	req.Header.Set("Sec-Fetch-Mode", "cors")
	req.Header.Set("Sec-Fetch-Site", "same-origin")
	req.Header.Set("Sec-GPC", "1")
	req.Header.Set("Pragma", "no-cache")
	req.Header.Set("Cache-Control", "no-cache")
	req.Header.Set("TE", "trailers")

	// 发送请求，失败则重试至多3次
	client := &http.Client{}
	resp, err := client.Do(req)
	for i := 0; i < 3 && err != nil; i++ {
		resp, err = client.Do(req)
	}
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// 处理压缩响应
	var reader io.Reader
	if resp.Header.Get("Content-Encoding") == "gzip" {
		reader, err = gzip.NewReader(resp.Body)
		if err != nil {
			return nil, err
		}
		defer reader.(*gzip.Reader).Close()
	} else {
		reader = resp.Body
	}

	// 解析响应体
	var playerData PlayerData
	err = json.NewDecoder(reader).Decode(&playerData)
	if err != nil {
		// log.Printf("got body %v", reader.)
		return nil, err
	}

	return &playerData, nil
}

func FetchCountryLeaderboard(country string, offset int, userId string) ([]PlayerDataLite, error) {
	if offset < 1 {
		offset = 1
	}
	url := fmt.Sprintf("https://api.beatleader.com/players?leaderboardContext=general&page=%d&count=50&sortBy=pp&mapsType=ranked&ppType=general&order=desc&countries=%s", (offset-1)/50+1, country)

	// 创建请求
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}

	// 设置请求头
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0")
	req.Header.Set("Accept", "application/json, text/plain, */*")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
	req.Header.Set("Accept-Encoding", "gzip")
	req.Header.Set("DNT", "1")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Referer", fmt.Sprintf("https://beatleader.xyz/u/%s/scores/date/desc/1", userId))
	req.Header.Set("Sec-Fetch-Dest", "empty")
	req.Header.Set("Sec-Fetch-Mode", "cors")
	req.Header.Set("Sec-Fetch-Site", "same-origin")
	req.Header.Set("Sec-GPC", "1")
	req.Header.Set("Pragma", "no-cache")
	req.Header.Set("Cache-Control", "no-cache")
	req.Header.Set("TE", "trailers")

	// 发送请求，失败则重试至多3次
	client := &http.Client{}
	resp, err := client.Do(req)
	for i := 0; i < 3 && err != nil; i++ {
		resp, err = client.Do(req)
	}
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// 处理压缩响应
	var reader io.Reader
	if resp.Header.Get("Content-Encoding") == "gzip" {
		reader, err = gzip.NewReader(resp.Body)
		if err != nil {
			return nil, err
		}
		defer reader.(*gzip.Reader).Close()
	} else {
		reader = resp.Body
	}

	// 解析响应体
	type Response struct {
		Data []PlayerDataLite `json:"data"`
	}
	var response Response
	err = json.NewDecoder(reader).Decode(&response)
	if err != nil {
		return nil, err
	}

	return response.Data, nil
}
