package main

import (
	"context"
	"fmt"
	"log"
	"math/rand"
	"net/url"
	"os"
	"time"

	common "github.com/prometheus/common/config"
	"github.com/prometheus/prometheus/prompb"
	"github.com/prometheus/prometheus/storage/remote"
	"gopkg.in/yaml.v2"
)

const configPath = "./test/integration/testdata/testdatagen-conf.yaml"

func main() {
	client, _ := remote.NewWriteClient("batch_simulator", &remote.ClientConfig{
		URL: mustParseURL("http://localhost:9090/api/v1/write"),
	})

	for {
		// 准备批量时间序列数据 (1000个指标)
		ts := make([]prompb.TimeSeries, 1000)
		for i := 0; i < 1000; i++ {
			ts[i] = prompb.TimeSeries{
				Labels: []prompb.Label{
					{Name: "__name__", Value: "batch_metric"},
					{Name: "instance", Value: fmt.Sprintf("%d", i)},
				},
				Samples: []prompb.Sample{
					{
						Value:     rand.Float64() * 100,
						Timestamp: time.Now().UnixNano() / int64(time.Millisecond),
					},
				},
			}
		}

		// 批量写入
		req := &prompb.WriteRequest{Timeseries: ts}
		payload, err := req.Marshal()
		if err != nil {
			log.Printf("Batch marshal error: %v", err)
			time.Sleep(10 * time.Second)
			continue
		}
		if _, err := client.Store(context.Background(), payload, 1); err != nil {
			log.Printf("Batch write error: %v", err)
		}

		time.Sleep(10 * time.Second)
	}
}

func mustParseURL(raw string) *common.URL {
	parsed, err := url.Parse(raw)
	if err != nil {
		panic(err)
	}
	return &common.URL{URL: parsed}
}

func loadConfig(path string) (*Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("failed to read config file: %w", err)
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		return nil, fmt.Errorf("failed to parse config: %w", err)
	}

	return &config, nil
}
