package main

import (
	"context"
	"flag"
	"fmt"
	"os/signal"
	"syscall"
	"time"

	"github.com/meilisearch/meilisearch-go"
)

func main() {
	var hostname, masterKey string
	var list bool
	flag.StringVar(&hostname, "host", "meili.zerops", "hostname to connect to elastic")
	flag.StringVar(&masterKey, "key", "nope", "master key")
	flag.BoolVar(&list, "list", false, "whether to list the whole index")
	flag.Parse()

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	client := meilisearch.New(fmt.Sprintf("http://%s:7700", hostname), meilisearch.WithAPIKey(masterKey))

	const indexName = "xxx"

	taskInfo, err := client.CreateIndexWithContext(ctx, &meilisearch.IndexConfig{
		Uid:        indexName,
		PrimaryKey: "id",
	})
	if err != nil {
		panic(err)
	}

	status := taskInfo.Status
	var taskErr any
	for status != "succeeded" {
		if status == "failed" || status == "canceled" {
			fmt.Println("task failed:", taskErr)
			break
		}
		task, err := client.GetTaskWithContext(ctx, taskInfo.TaskUID)
		if err != nil {
			panic(err)
		}
		status = task.Status
		taskErr = task.Error
	}

	indices, err := client.ListIndexesWithContext(ctx, &meilisearch.IndexesQuery{})
	if err != nil {
		panic(err)
	}
	for _, index := range indices.Results {
		fmt.Println(index.UID, index.PrimaryKey)
	}

	index := client.Index(indexName)

	if list {
		resp, err := index.SearchWithContext(ctx, "*", &meilisearch.SearchRequest{Limit: 1024 * 1024})
		if err != nil {
			panic(err)
		}
		for _, hit := range resp.Hits {
			fmt.Printf("LIST: ==> %s\n", hit.(map[string]any)["message"])
		}
	}

	for {
		if ctx.Err() != nil {
			fmt.Println("context canceled")
			return
		}

		now := time.Now()
		message := now.Format(time.TimeOnly)
		document := map[string]any{
			"id":      now.UnixNano(),
			"name":    "meili",
			"message": message,
		}
		taskInfo, err = index.AddDocumentsWithContext(ctx, []map[string]any{document})
		if err != nil {
			panic(err)
		}

		status = taskInfo.Status
		for status != "succeeded" {
			if status == "failed" || status == "canceled" {
				fmt.Println("task failed:", taskErr)
				break
			}
			task, err := index.GetTaskWithContext(ctx, taskInfo.TaskUID)
			if err != nil {
				panic(err)
			}
			status = task.Status
			taskErr = task.Error
		}
		fmt.Printf("==> %s\n", document["message"])

		time.Sleep(time.Second)
	}
}
