package main

import (
	"encoding/json"
	"fmt"

	"go.wit.com/lib/protobuf/chatpb"
	"go.wit.com/log"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func doStats() {
	if len(argv.Stats) != 2 {
		log.Error(fmt.Errorf("expected 2 arguments for --stats"))
		return
	}
	sessionUuid := argv.Stats[0]
	statsString := argv.Stats[1]

	// Find the "auto" chat, or create it if it doesn't exist.
	var autoChat *chatpb.Chat
	for _, chat := range me.chats.GetChats() {
		if chat.GetChatName() == "auto" {
			autoChat = chat
			break
		}
	}
	if autoChat == nil {
		autoChat = &chatpb.Chat{
			ChatName: "auto",
			Ctime:    timestamppb.Now(),
		}
		me.chats.Chats = append(me.chats.Chats, autoChat)
	}

	var stats chatpb.SessionStats
	err := json.Unmarshal([]byte(statsString), &stats)
	if err != nil {
		log.Error(fmt.Errorf("error unmarshalling stats: %w", err))
		return
	}

	// The session UUID from the command line is the UUID of the session.
	stats.Uuid = sessionUuid

	autoChat.Session = append(autoChat.Session, &stats)
	me.chats.ConfigSave()
	log.Info("stats saved for session", sessionUuid, "in chat", autoChat.GetChatName())
}
