// Copyright 2017-2025 WIT.COM Inc. All rights reserved.
// Use of this source code is governed by the GPL 3.0

package main

// An app to submit patches for the 30 GO GUI repos

import (
	"embed"
	"os"

	"github.com/google/uuid"
	"go.wit.com/dev/alexflint/arg"
	"go.wit.com/gui"
	"go.wit.com/lib/protobuf/chatpb"
	"go.wit.com/log"
)

// sent via -ldflags
var VERSION string
var BUILDTIME string

// this optionally can store the GUI plugins
//
//go:embed resources/*
var resources embed.FS

// used for shell auto completion
var ARGNAME string = "regex"

// using this for now. triggers config save
var configSave bool

func main() {
	me = new(mainType)
	gui.InitArg()
	me.pp = arg.MustParse(&argv)

	if argv.Bash {
		argv.doBash()
		os.Exit(0)
	}
	if len(argv.BashAuto) != 0 {
		argv.doBashAuto()
		os.Exit(0)
	}

	me.chats = chatpb.NewChats()
	if err := me.chats.ConfigLoad(); err != nil {
		badExit(err)
	}
	if verifyUuids(me.chats) {
		me.chats.ConfigSave()
	}

	if argv.GetNextAutoTopic {
		doGetNextAutoTopic()
		okExit("")
	}

	if argv.NewChat != nil {
		doNewChat()
		okExit("")
	}

	if argv.Stats != nil {
		doStats()
		okExit("")
	}

	if argv.Output != "" {
		doOutput(argv.Output)
		okExit("")
	}

	if argv.Input != "" {
		doInput(argv.Input)
		okExit("")
	}

	if argv.ImportFile != "" {
		doImport(argv.ImportFile)
		okExit("")
	}

	if argv.Add != "" {
		newChats, err := addFile(argv.Add)
		if err != nil {
			badExit(err)
		}
		verifyUuids(newChats)

		for _, newChat := range newChats.GetChats() {
			me.chats.AppendByUuid(newChat)
			log.Info("Attempting to add chat", newChat.ChatName)
		}

		me.chats.ConfigSave()
		okExit("")
	}

	if argv.Playback != nil {
		if argv.Playback.Uuid != "" {
			showChat(argv.Playback.Uuid)
		} else {
			doPlayback()
		}
		okExit("")
	}

	// if opening the GUI, always check git for dirty repos
	log.Info("look for 'auto' here")
	// Find the "auto" chat.
	for _, chat := range me.chats.GetChats() {
		if chat.GetChatName() == "auto" {
			prettyFormatChat(chat)
			okExit("")
		}
	}
	// doGui()
	okExit("")
}

func verifyUuids(chats *chatpb.Chats) bool {
	var changed bool
	for _, chat := range chats.GetChats() {
		if chat.GetUuid() == "" {
			chat.Uuid = uuid.New().String()
			changed = true
		}
		for _, entry := range chat.GetEntries() {
			if entry.GetUuid() == "" {
				entry.Uuid = uuid.New().String()
				changed = true
			}
		}
	}
	return changed
}
