package main

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/42wim/matterbridge/bridge/config"
	"github.com/42wim/matterbridge/gateway"
	"github.com/42wim/matterbridge/gateway/bridgemap"
	"github.com/42wim/matterbridge/version"
	"github.com/google/gops/agent"
	prefixed "github.com/matterbridge/logrus-prefixed-formatter"
	"github.com/sirupsen/logrus"
)

var (
	flagConfig  = flag.String("conf", "matterbridge.toml", "config file")
	flagDebug   = flag.Bool("debug", false, "enable debug")
	flagVersion = flag.Bool("version", false, "show version")
	flagGops    = flag.Bool("gops", false, "enable gops agent")
	flagMuted   = flag.Bool("muted", false, "start with Jackbox announcements muted")
)

func main() {
	flag.Parse()
	if *flagVersion {
		fmt.Printf("version: %s %s\n", version.Release, version.GitHash)
		return
	}

	rootLogger := setupLogger()
	logger := rootLogger.WithFields(logrus.Fields{"prefix": "main"})

	if *flagGops {
		if err := agent.Listen(agent.Options{}); err != nil {
			logger.Errorf("Failed to start gops agent: %#v", err)
		} else {
			defer agent.Close()
		}
	}

	logger.Printf("Running version %s %s", version.Release, version.GitHash)
	if strings.Contains(version.Release, "-dev") {
		logger.Println("WARNING: THIS IS A DEVELOPMENT VERSION. Things may break.")
	}
	
	// Debug: Log muted flag state
	if *flagMuted {
		logger.Info("Muted flag detected: --muted")
	}

	cfg := config.NewConfig(rootLogger, *flagConfig)
	cfg.BridgeValues().General.Debug = *flagDebug

	// if logging to a file, ensure it is closed when the program terminates
	// nolint:errcheck
	defer func() {
		if f, ok := rootLogger.Out.(*os.File); ok {
			f.Sync()
			f.Close()
		}
	}()

	r, err := gateway.NewRouter(rootLogger, cfg, bridgemap.FullMap)
	if err != nil {
		logger.Fatalf("Starting gateway failed: %s", err)
	}
	
	// Set initial mute state BEFORE starting (so it's set when callbacks are created)
	if *flagMuted && r.JackboxManager != nil {
		r.JackboxManager.SetMuted(true)
		logger.Warn("🔇 Jackbox announcements starting MUTED (use SIGUSR1 to toggle)")
	}
	
	// Setup signal handler for mute toggle (before starting)
	setupMuteToggle(r, logger)
	
	if err = r.Start(); err != nil {
		logger.Fatalf("Starting gateway failed: %s", err)
	}
	
	logger.Printf("Gateway(s) started successfully. Now relaying messages")
	select {}
}

func setupMuteToggle(r *gateway.Router, logger *logrus.Entry) {
	if r.JackboxManager == nil {
		return
	}
	
	// Create channel for SIGUSR1 signal
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGUSR1)
	
	// Start goroutine to handle signal
	go func() {
		for range sigChan {
			isMuted := r.JackboxManager.ToggleMuted()
			if isMuted {
				logger.Warn("🔇 Jackbox announcements MUTED")
			} else {
				logger.Info("🔊 Jackbox announcements UNMUTED")
			}
		}
	}()
	
	logger.Info("Signal handler ready: Send SIGUSR1 to toggle mute (kill -SIGUSR1 <pid> or docker kill -s SIGUSR1 <container>)")
}

func setupLogger() *logrus.Logger {
	logger := &logrus.Logger{
		Out: os.Stdout,
		Formatter: &prefixed.TextFormatter{
			// PrefixPadding: 13,  // Not supported in this version
			DisableColors: true,
		},
		Level: logrus.InfoLevel,
	}
	if *flagDebug || os.Getenv("DEBUG") == "1" {
		logger.SetReportCaller(true)
		logger.Formatter = &prefixed.TextFormatter{
			// PrefixPadding: 13,  // Not supported in this version
			DisableColors: true,
			FullTimestamp: false,
			// CallerFormatter and CallerPrettyfier not supported in this version
		}

		logger.Level = logrus.DebugLevel
		logger.WithFields(logrus.Fields{"prefix": "main"}).Info("Enabling debug logging.")
	}
	return logger
}
