package main

import (
	"bufio"
	"context"
	"fmt"
	"os"
	"strings"

	"bindbox-game/internal/pkg/wechat"
)

func main() {
	// 1. Load config
	appID, appSecret := loadConfig("../../configs/fat_configs.toml")
	if appID == "" || appSecret == "" {
		fmt.Println("Failed to load Wechat config from ../../configs/fat_configs.toml")
		// Fallback to current dir if run from root
		appID, appSecret = loadConfig("configs/fat_configs.toml")
		if appID == "" || appSecret == "" {
			fmt.Println("Failed to load Wechat config from configs/fat_configs.toml")
			return
		}
	}
	fmt.Printf("Loaded Config: AppID=%s\n", appID)

	// 2. Get Access Token
	ctx := context.Background()
	cfg := &wechat.WechatConfig{AppID: appID, AppSecret: appSecret}
	at, err := wechat.GetAccessTokenWithContext(ctx, cfg)
	if err != nil {
		fmt.Printf("Failed to get access token: %v\n", err)
		return
	}
	fmt.Println("Got Access Token successfully")

	// 3. Test Params
	token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvd25lcl91c2VyX2lkIjo5MDUzLCJpbnZlbnRvcnlfaWQiOjI4NzQ5LCJleHAiOjE3Njc5MzIwOTcsIm5iZiI6MTc2NzkyODQ5NywiaWF0IjoxNzY3OTI4NDk3fQ.8dQuqbJj7hlDlBtdNkTXnJaq7y0qOwefzP5XbhSrE10"
	pagePath := fmt.Sprintf("pages-user/address/submit?token=%s", token)
	schemePath := "pages-user/address/submit"
	schemeQuery := fmt.Sprintf("token=%s", token)

	// 4. Test GetShortLink
	fmt.Println("\nTesting GetShortLink...")
	// Test Case A: Current Target (Subpackage)
	sl, err := wechat.GetShortLink(at, pagePath, "Test Title")
	if err != nil {
		fmt.Printf("Case A (Subpackage) Failed: %v\n", err)
	} else {
		fmt.Printf("Case A (Subpackage) Success: %s\n", sl)
	}

	// Test Case B: Main Page (Known good)
	slMain, err := wechat.GetShortLink(at, "pages/index/index", "Main Page")
	if err != nil {
		fmt.Printf("Case B (Main Page) Failed: %v\n", err)
	} else {
		fmt.Printf("Case B (Main Page) Success: %s\n", slMain)
	}

	// Test Case C: Leading Slash
	slSlash, err := wechat.GetShortLink(at, "/"+pagePath, "Slash Path")
	if err != nil {
		fmt.Printf("Case C (Leading Slash) Failed: %v\n", err)
	} else {
		fmt.Printf("Case C (Leading Slash) Success: %s\n", slSlash)
	}

	// 5. Test GenerateScheme (Release)
	fmt.Println("\nTesting GenerateScheme (Release)...")
	sch, err := wechat.GenerateScheme(at, schemePath, schemeQuery, "release")
	if err != nil {
		fmt.Printf("GenerateScheme (Release) Failed: %v\n", err)
	} else {
		fmt.Printf("GenerateScheme (Release) Success: %s\n", sch)
	}

	// 6. Test GenerateScheme (Trial)
	fmt.Println("\nTesting GenerateScheme (Trial)...")
	schTrial, err := wechat.GenerateScheme(at, schemePath, schemeQuery, "trial")
	if err != nil {
		fmt.Printf("GenerateScheme (Trial) Failed: %v\n", err)
	} else {
		fmt.Printf("GenerateScheme (Trial) Success: %s\n", schTrial)
	}

	// 7. Test Length with Short Token
	fmt.Println("\nTesting GenerateScheme with Short Token (Release)...")
	shortToken := "short_token_123"
	schShort, err := wechat.GenerateScheme(at, schemePath, fmt.Sprintf("token=%s", shortToken), "release")
	if err != nil {
		fmt.Printf("GenerateScheme (Short Token) Failed: %v\n", err)
	} else {
		fmt.Printf("GenerateScheme (Short Token) Success: %s\n", schShort)
	}
}

func loadConfig(path string) (string, string) {
	f, err := os.Open(path)
	if err != nil {
		return "", ""
	}
	defer f.Close()

	var appId, appSecret string
	scanner := bufio.NewScanner(f)
	inWechat := false
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if strings.ToLower(line) == "[wechat]" {
			inWechat = true
			continue
		}
		if strings.HasPrefix(line, "[") && line != "[wechat]" && line != "[Wechat]" {
			inWechat = false
		}
		if inWechat {
			if strings.HasPrefix(line, "app_id") {
				parts := strings.Split(line, "=")
				if len(parts) == 2 {
					appId = strings.Trim(strings.TrimSpace(parts[1]), "\"")
				}
			}
			if strings.HasPrefix(line, "app_secret") {
				parts := strings.Split(line, "=")
				if len(parts) == 2 {
					appSecret = strings.Trim(strings.TrimSpace(parts[1]), "\"")
				}
			}
		}
	}
	return appId, appSecret
}
