package main

import (
	"context"
	"encoding/json"

	"net/http"
	"os"
	"testing"
	"time"

	confMetrics "github.com/pingcap-inc/clinic/clinic_data_service/pkg/config/metrics"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/constant"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/dto"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/handlers"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/log"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/service"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/thirdapi/aws"
	"github.com/pingcap-inc/clinic/clinic_data_service/pkg/utils"
	"go.uber.org/zap"
)

const (
	pngDir          = "/Users/wlt/Documents/GolandProjects/clinic/health_check/clinic_data_service/output" // img output dir
	pythonScriptDir = "/Users/wlt/Documents/GolandProjects/clinic/health_check/convert-image"              // python script dir
	csvDir          = pythonScriptDir + "/prod/data"
)

func mustParse(s string) time.Time {
	tm, err := time.Parse(time.RFC3339, s)
	if err != nil {
		log.PlainError("parse time failed: %v", zap.Error(err))
	}
	return tm
}

func TestComparePerformance(t *testing.T) {
	confMetrics.InitForMetrics()

	Init()
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	prod := "10892260000245137880"
	replay := "10892260000245137880" //gogame-cdc-replay

	prodTimeStr := "2026-03-06T16:00:00+08:00"   // require
	replayStart01 := "2026-03-06T16:00:00+08:00" // require

	// Parse time strings
	prodStart01, err := time.Parse(time.RFC3339, prodTimeStr)
	if err != nil {
		t.Fatalf("Parse prod time failed: %v", err)
	}
	// aStart := &prodTimeStr
	prodEnd := prodStart01.Add(24 * time.Hour).Add(0 * time.Minute) //  // require

	testStartTime, err := time.Parse(time.RFC3339, replayStart01)
	if err != nil {
		t.Fatalf("Parse test time failed: %v", err)
	}
	testEndTime := testStartTime.Add(24 * time.Hour).Add(0 * time.Minute) // require
	// BStart := &replayStart01

	//var diffKeys = []string{
	//	"latency_p99", // P99 latency
	//	"latency_p95", // P95 latency
	//	"latency_avg", // Average latency
	//}
	req := &dto.CompareRequest{
		ClusterA: dto.ClusterSideDTO{
			ClusterId: prod,
			TimeRange: dto.TimeRange{
				Start: prodStart01,
				End:   prodEnd,
			},
			PhysicalClusterID: "2026949624178147328",
			DeployType:        string(constant.DeployTypePremium),
			ClusterUrls: dto.ClusterUrls{
				ClusterMetricsURL:   "https://www.ds.cn-hongkong.alicloud.observability.tidbcloud.com/internal/v2/metrics/multitenant/api/v1/",
				DataPlaneMetricsURL: "https://www.ds.cn-hongkong.alicloud.observability.tidbcloud.com/internal/v2/metrics/multitenant/api/v1/",
			},
		},
		ClusterB: dto.ClusterSideDTO{
			ClusterId: replay,
			TimeRange: dto.TimeRange{
				Start: testStartTime,
				End:   testEndTime,
			},
			Provider:          string(constant.ProviderAWS),
			DeployType:        string(constant.DeployTypePremium),
			PhysicalClusterID: "2026949624178147328",
			ClusterUrls: dto.ClusterUrls{
				ClusterMetricsURL:   "https://www.ds.cn-hongkong.alicloud.observability.tidbcloud.com/internal/v2/metrics/multitenant/api/v1/",
				DataPlaneMetricsURL: "https://www.ds.cn-hongkong.alicloud.observability.tidbcloud.com/internal/v2/metrics/multitenant/api/v1/",
			},
		},
		Interval: "1m",
		DiffKeys: nil,
		// CsvDir:        csvDir,
	}

	svc := service.NewMetricsDiffApiService()
	response, err := svc.CompareClusterPerformance(ctx, req)
	if err != nil {
		t.Fatalf("CompareClusterPerformance failed: %v", err)
	}
	if response != nil {
		jsonBytes, err := json.MarshalIndent(response, "", "  ")
		if err != nil {
			t.Fatalf("Failed to marshal response to JSON: %v", err)
		}

		jsonFilePath := "./output/metrics_diff.json"
		if err := os.WriteFile(jsonFilePath, jsonBytes, 0644); err != nil {
			t.Fatalf("Failed to write JSON file: %v", err)
		}
		t.Logf("Response saved to %s", jsonFilePath)
	}

}

func TestUploadToS3(t *testing.T) {
	aws.UploadFileToS3("./output/compare_result.json", "traffic-comparison-report/compare_result.json")
}

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

	aStart := "2026-01-02T13:00:00+08:00" // require
	bStart := "2026-01-02T13:15:00+08:00" // require
	//
	// aStart := "2025-12-24T16:20:33Z" // require
	// bStart := "2025-12-25T16:21:33Z" // require
	topN := 2

	aEnd := mustParse(aStart).Add(6 * time.Hour).Add(0 * time.Minute) // require
	bEnd := mustParse(bStart).Add(6 * time.Hour).Add(0 * time.Minute) // require

	diffParam := dto.QueryComparisonRequest{
		ClusterA: dto.ClusterSideDTO{
			ClusterId:  "10602564149339879488",
			TenantID:   "1372813089201471287",
			ProjectID:  "1372813089199431289",
			Provider:   string(constant.ProviderGCP),
			DeployType: string(constant.DeployTypeDedicated),
			Region:     "asia-northeast1",
			TimeRange: dto.TimeRange{
				Start: mustParse(aStart),
				End:   aEnd,
			},
		},
		ClusterB: dto.ClusterSideDTO{
			ClusterId:  "10602564149339879488",
			TenantID:   "1372813089201471287",
			ProjectID:  "1372813089199431289",
			Provider:   string(constant.ProviderGCP),
			DeployType: string(constant.DeployTypeDedicated),
			Region:     "asia-northeast1",
			TimeRange: dto.TimeRange{
				Start: mustParse(bStart),
				End:   bEnd,
			},
		},
		Options: dto.QueryComparisonOptions{
			TopN:           topN,
			DigestDiffKeys: []string{"topSqlDigestDiff", "slowQueryDigestDiff", "topSqlDigestDiff"},
		},
		// DigestDiffKeys: []string{  "slowQueryCountDiff" },
		// DigestDiffKeys: []string{  "slowQueryDigestDiff" },
		// DigestDiffKeys: []string{  "topSqlDigestDiff" },

	}
	handlers.ClusterSqlDiff(context.Background(), diffParam, "")
}

func TestCreateReport(t *testing.T) {
	//https://us-west-2.nightly.shared.aws.tidbcloud.com/api/v1/admin/rbac/role/list

	host := "http://127.0.0.1:8087"
	url := "/traffic-mirroring/report"
	header := map[string]string{
		"contentType": "application/json",
	}
	/*
		data := `{
					"clusterA": {
						"clusterId": "1379661944646416027",
						"alias": "prod",
						"region": "us-east-1",
						"deployType": "dedicated",
						"provider": "aws",
						"urls":{
							"clusterMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/ed869d81-91c5-4a87-a28d-20795c738d3f/api/v1/",
							"dataPlaneMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/0c252928-4d3c-4029-b157-8b866adb3d67/api/v1/",
							"slowQueryS3Url": "s3://o11y-prod-shared-us-east-1/deltalake/1372813089209061633/ed869d81-91c5-4a87-a28d-20795c738d3f/slowlogs"
						},
						"timeRange": {
							"start": "2025-12-20T11:29:14+08:00",
							"end":   "2025-12-22T11:29:14+08:00"
						}
					},
					"clusterB": {
						"clusterId": "1379661944646416027",
						"alias": "replay",
						"region": "us-east-1",
						"deployType": "dedicated",
						"provider": "aws",
							"provider": "aws",
						"urls":{
							"clusterMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/ed869d81-91c5-4a87-a28d-20795c738d3f/api/v1/",
							"dataPlaneMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/0c252928-4d3c-4029-b157-8b866adb3d67/api/v1/",
							"slowQueryS3Url": "s3://o11y-prod-shared-us-east-1/deltalake/1372813089209061633/ed869d81-91c5-4a87-a28d-20795c738d3f/slowlogs"
						},
						"timeRange": {
							"start": "2025-12-20T12:00:00+08:00",
							"end":   "2025-12-22T12:00:00+08:00"
						}
					},
					"options": {
						"topN": 2,
						"digestDiffKeys": ["slowQueryCountDiff" ,"slowQueryDigestDiff","topSqlDigestDiff"]
					}
				}`

	*/

	data := `{
				
			"callBackUrl": "",
			"clusterA": {
				"clusterId": "1379661944646416054",
				"alias": "1379661944646416054",
				"timeRange": {
				"Start": "2025-12-31T19:11:30Z",
				"End": "2026-01-01T01:11:30Z"
				},
				"clusterUrls": {
				"clusterMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/bb9e1b4a-25bb-4ed0-b5ec-58a4572b22dd/api/v1/",
				"dataPlaneMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/0c252928-4d3c-4029-b157-8b866adb3d67/api/v1/",
				"slowQueryS3Url": "s3://o11y-prod-shared-us-east-1/deltalake/1372813089209061633/bb9e1b4a-25bb-4ed0-b5ec-58a4572b22dd/slowlogs"
				},
				"provider": "aws",
				"region": "us-east-1",
				"deployType": "dedicated",
				"tenantId": "1372813089209061633",
				"projectId": "1372813089454544954"
			},
			"clusterB": {
				"clusterId": "10518506906906971664",
				"alias": "10518506906906971664",
				"timeRange": {
				"Start": "2026-01-01T05:15:00Z",
				"End": "2026-01-01T11:15:00Z"
				},
				"clusterUrls": {
				"clusterMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/019b6fb8-07aa-7e47-981b-6bd662f2949b/api/v1/",
				"dataPlaneMetricsUrl": "https://www.ds.us-east-1.aws.observability.tidbcloud.com/internal/metrics/0c252928-4d3c-4029-b157-8b866adb3d67/api/v1/",
				"slowQueryS3Url": "s3://o11y-prod-shared-us-east-1/deltalake/1372813089209061633/019b6fb8-07aa-7e47-981b-6bd662f2949b/slowlogs"
				},
				"provider": "aws",
				"region": "us-east-1",
				"deployType": "dedicated",
				"tenantId": "1372813089209061633",
				"projectId": "1372813089454544954"
			},
			"options": {
				"topN": 1,
				"digestDiffKeys": [
				"slowQueryDigestDiff-",
				"topSqlDigestDiff-",
				"slowQueryCountDiff-"
				]
			}
		

 	
 		}`
	ctx := context.Background()
	resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
	if err != nil {
		log.PlainError("HttpRequest failed", zap.Error(err))
	}

	log.PlainInfo("TestCreateReport success", zap.Any("resp", resp))
}
func TestSqlDiffApi(t *testing.T) {
	//https://us-west-2.nightly.shared.aws.tidbcloud.com/api/v1/admin/rbac/role/list

	host := "http://127.0.0.1:8087"
	url := "/traffic-mirroring/query-comparison"
	header := map[string]string{
		"contentType": "application/json",
	}
	/*  wetech
	data := `{
				"clusterA": {
					"clusterId": "1379661944646416027",
					"alias": "prod",
					"region": "us-east-1",
					"deployType": "dedicated",
					"provider": "aws",
					"tenantID": "1372813089209061633",
					"timeRange": {
						"start": "2025-12-20T11:29:14+08:00",
						"end":   "2025-12-22T11:29:14+08:00"
					}
				},
				"clusterB": {
					"clusterId": "1379661944646416027",
					"alias": "replay",
					"region": "us-east-1",
					"deployType": "dedicated",
					"provider": "aws",
					"tenantID": "1372813089209061633",
					"timeRange": {
						"start": "2025-12-20T12:00:00+08:00",
						"end":   "2025-12-22T12:00:00+08:00"
					}
				},
				"options": {
					"topN": 3,
					"digestDiffKeys": ["slowQueryCountDiff" ,"slowQueryDigestDiff","topSqlDigestDiff2"]
				}
			}`

	*/
	data := `{
				"clusterA": {
					"clusterId": "10708781521961418851",
					"alias": "prod",
					"region": "us-east-1",
					"deployType": "dedicated",
					"provider": "aws",
					"tenantId": "1372813089188151296",
					"ProjectId": "1372813089454583500",
					"timeRange": {
						"start": "2025-12-20T11:29:14+08:00",
						"end":   "2025-12-22T11:29:14+08:00"
					}
				},
				"clusterB": {
					"clusterId": "10708781521961418851",
					"alias": "replay",
					"region": "us-east-1",
					"deployType": "dedicated",
					"provider": "aws",
					"tenantId": "1372813089188151296",
					"ProjectId": "1372813089454583500",
					"timeRange": {
						"start": "2025-12-20T12:00:00+08:00",
						"end":   "2025-12-22T12:00:00+08:00"
					}
				},
				"options": {
					"topN": 3,
					"digestDiffKeys": ["slowQueryCountDiff" ,"slowQueryDigestDiff","topSqlDigestDiff2"]
				}
			}`
	ctx := context.Background()
	resp, err := utils.HttpRequest(ctx, *utils.NewHttpConfig(host, url, http.MethodPost, header, utils.BodyJson(data)))
	if err != nil {
		log.PlainError("HttpRequest failed", zap.Error(err))
	}

	log.PlainInfo("TestCreateReport success", zap.Any("resp", resp))
}
