package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"testing"

	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/common"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/config"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/dto"
	log2 "github.com/pingcap-inc/clinic/clinic_data_service/pkg/log"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/parser"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/query"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/s3"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/thirdapi/feishu"
	"go.uber.org/zap"
)

// Command line parameters for testing
var testFiles = flag.String("test_files", "", "List of files to upload, separated by commas")
var testTarget = flag.String("test_target", "", "Target S3 prefix path for upload")

// Test in pod
func TestPodSlowQuery(t *testing.T) {
	Init()
	ctx := log2.StartTrace("TestPodSlowQuery", "")
	defer log2.EndTrace(ctx)
	// 1、Test metrics health check
	RunMetricsHealthCheck()

	// 2、Test slow query check
	startS3Download(ctx)
	startLocalSlowQueryCheck(ctx)
}
func TestSlowQueryCheckDaily(t *testing.T) {
	ctx := log2.StartTrace("TestSlowQueryCheckDaily", "")
	defer log2.EndTrace(ctx)
	Init()
	// 2、Test slow query check
	startS3Download(ctx)
	startLocalSlowQueryCheck(ctx)
}

// Local test to read local s3 files and generate report
func TestLocalSlowQuery(t *testing.T) {
	Init()
	ctx := context.Background()
	startLocalSlowQueryCheck(ctx)
}

// Test direct query of SqlLite data and write Feishu document
func TestWriteDoc(t *testing.T) {
	Init()
	ctx := context.Background()
	// Test case 1: Use s3.S3Statistics struct
	stats := s3.S3Statistics{
		SlowQueryCount: 85298,
	}

	// Convert stats to interface{}
	var statsInterface interface{} = stats
	org := config.OrgsConfig.Orgs[0]

	// Create QuerySqlLite instance
	querySqlLite, err := query.NewQuerySqlLite(ctx, org)
	if err != nil {
		log2.PlainError("Failed to create QuerySqlLite", zap.Error(err))
	}
	defer querySqlLite.Close()

	// Call function
	finalOutput, err := querySqlLite.RunS3SlowQueryAnalysis(ctx, statsInterface)
	if err != nil {
		log2.PlainError("RunS3SlowQueryAnalysis returned error", zap.Error(err))
		return

	}
	log2.PlainInfo("RunS3SlowQueryAnalysis completed successfully")

	// 3. Write Feishu document
	feishu.NewReportWriter(org).WriteResult(*finalOutput)

	// 4. Write Feishu group card
	feishu.SendMessageCard(*finalOutput, org.ReceiveID...)

}

// Usage example
func TestBinaryPlan(t *testing.T) {
	Init()
	log2.PlainInfo("=============TestBinaryPlan Start===========")
	binaryPlanStr := "tidb_decode_binary_plan('1B2QCs8dCgxQcm9qZWN0aW9uXzUSuRsKCUhhc2hBZ2dfNhLRGAoNUBkfcDE1ErsUCg5JbmRleExvb2tVcF8xNBKtCQoMU2VsDUMYMTIS5QIKEQUk8MlSYW5nZVNjYW5fMTAhaQy8lrf/eEApDlvHYMKC8j8w3KwQOAJAAkp7CnkKC2RoX2FwcF81NjE3EhdkaF9wcm9tb3RlX3JlZmVyX2RvbWFpbhpRCh1pZHhfeW1kX2tpbmRfZG9tYWluX25vZGVfc2l0ZRIKY3JlYXRlX3ltZBIEa2luZBIGZG9tYWluEgtkb21haW5fbm9kZRIJc2l0ZV9jb2RlUkhyYW5nZTpbMjAyNTA2MjQgMywyMDI1MDYyNCAzXSwgWzIwMjUwARkENCwVGfBSNF0sIGtlZXAgb3JkZXI6ZmFsc2VqWXRpa3ZfdGFzazp7cHJvYyBtYXg6MTAwbXMsIG1pbjowcywgYXZnOiA0MS41bXMsIHA4MDo4MG1zLCBwOTURKihpdGVyczozMTMsIAFLGHM6MTN9cP8RAQQBeBEKMP8BGgEBIUEVCOKLG4BGVQEUUnRlcShkOVQALlpTAQQuczEKCCwgIiF9DCIpLCDiOwAkWhV0aW1lOjY4OQH1OGxvb3BzOjI2NWKeAmNvcCkbGCB7bnVtOiAB4CRtYXg6IDE1Ni40AS4hIxAgMy40NwENJSgMNTQuMgENIR4dKARheEEdNGNfa2V5czogNTAxNDQsASRK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IDcyNQHuQGZldGNoX2hhbmRsZTogNzA46R7FiRQ6IDIyLjVF9kmeBDE2BaKBBQhibGVOVgAYMy4xMXMsIOl0CDcsIDJoAig1fSwgbmV4dDogewFQAF8FnAw6IDk3CXQFFAB0BVoYbG9va3VwXxGGADgBdwAsSiEASHJlc3A6IDgxNC41bXN9cNCllgsqsggcIdUrubHRE6JGMgEIUq4Djq0IjYZMaWQtPkNvbHVtbiMyMywgY2FzZSiatAiJwRQzKSwgMSkZRQA0zkUAADQ6RQAINSwgqsQAAYkZgQA2ljwAtUsZOgA3ljoALTo2dgAAOJY8AEp2AAA5UeMEODaplVnjCA9DbyYLCRRPRkZwrIIyBAIkDrPoHUl2rkApAAUBDPA/MANhNCxSpQJncm91cCBieTox3Ag4LCARCyA5LCBmdW5jczplwgAooVIMaW5jdBUgADM5zg5jCS4sABFDADQdIwA0Nk8AESMANR0jADURIxxmaXJzdHJvdxUmDDYpLT666gFiTAAAN5pMADWEBFoThS8MMS4xNPk7LHCs/rsBIZ+gZV0+i0ZaAQS2AQ7ZC1UzBDE2tu4CXTthNjQsIGFuZHJvaWQsIGlvcz0xmooCFco13SGxLYIhmRELADVS6wBGYAI47A54////////////ARgB')"
	// binaryPlanStr := "tidb_decode_binary_plan('your_base64_encoded_data_here')"
	result, err := parser.ParseBinaryPlan(binaryPlanStr)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	// Convert result to JSON format and print
	jsonBytes, err := json.MarshalIndent(result, "", "  ")
	if err != nil {
		fmt.Printf("JSON marshal error: %v\n", err)
		return
	}
	log2.PlainInfo("Parsed result (JSON):\n%s\n" + string(jsonBytes))
	log2.PlainInfo("=============TestBinaryPlan End===========")
}

// Feishu message test
func TestPushFeishuMessage(t *testing.T) {
	Init()
	msg := fmt.Sprintf("Slow Query analysis result: %s", config.AppConfig.Feishu.DocumentUrl)
	msgJson := fmt.Sprintf(`{"text":"%s"}`, msg)
	// Send Feishu message
	feishu.SendMessageWithJson(msgJson)
}

func TestSendMessageCard(t *testing.T) {
	Init()
	finalOutput := buildFromFile("./output/20250723-wetech-result.json")
	// Send Feishu message
	feishu.SendMessageCard(finalOutput)
}

// buildFromFile reads data from JSON file and constructs dto.FinalOutput object
func buildFromFile(filePath string) dto.FinalOutput {
	finalOutput, err := parser.ReadJSONOutput(filePath)
	if err != nil {
		log2.PlainError("Failed to read JSON file", zap.String("file", filePath), zap.Error(err))
		return dto.FinalOutput{}
	}
	return *finalOutput
}

// Download files from s3
func TestDownloadS3Files(t *testing.T) {
	Init()
	ctx := context.Background()
	startS3Download(ctx)
}
func TestDownloadOneFile(t *testing.T) {
	Init()
	ctx := context.Background()
	// wetech
	clusterId := "1379661944646416027"

	day := "20251020"
	prefixHour := "07"
	s3.DownloadS3Files(ctx, clusterId, day, prefixHour)
}

func TestListFilesByTimeRange(t *testing.T) {
	Init()
	clusterId := "1379661944646416027"

	cluster, err := common.GetCluster(context.Background(), clusterId)
	if err != nil {
		log2.PlainError("Failed to get cluster", zap.String("cluster", clusterId), zap.Error(err))
		return
	}

	s3Client, _ := s3.GetS3ClientByGithubToken(cluster.Region)
	// dtoCluster := dto.Cluster{
	// 	ClusterID: cluster.ClusterID,
	// 	// OrgID:     cluster.OrgID,
	// 	MetricsRouting: cluster.MetricsRouting,
	// 	Region:         cluster.Region,
	// }
	files, err := s3.ListFilesByTimeRange(*s3Client, clusterId)
	if err != nil {
		t.Fatalf("Failed to list files: %v", err)
	}
	t.Log(len(files))
	t.Logf("Files: %v", files)
}

func TestS3ApieKey(t *testing.T) {
	Init()

	region := "ap-southeast-1"
	s3Client, _ := s3.GetS3ClientByGithubToken(region)

	log2.PlainInfo("s3Client: %v", zap.Any("s3Client", s3Client))

}
