package main

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

	"github.com/42wim/matterbridge/bridge"
	bkosmi "github.com/42wim/matterbridge/bridge/kosmi"
	"github.com/sirupsen/logrus"
)

func main() {
	// Parse command line flags
	roomURL := flag.String("room", "https://app.kosmi.io/room/@hyperspaceout", "Kosmi room URL")
	debug := flag.Bool("debug", false, "Enable debug logging")
	flag.Parse()

	// Set up logger
	log := logrus.New()
	if *debug {
		log.SetLevel(logrus.DebugLevel)
	} else {
		log.SetLevel(logrus.InfoLevel)
	}
	log.SetFormatter(&logrus.TextFormatter{
		FullTimestamp: true,
	})

	logger := log.WithField("bridge", "kosmi-test")

	logger.Info("Starting Kosmi bridge test")
	logger.Infof("Room URL: %s", *roomURL)

	// Create bridge configuration
	cfg := bridge.NewConfig("kosmi.test", logger)
	cfg.SetString("RoomURL", *roomURL)
	cfg.SetBool("Debug", *debug)

	// Create Kosmi bridge
	b := bkosmi.New(cfg)

	// Connect to Kosmi
	logger.Info("Connecting to Kosmi...")
	if err := b.Connect(); err != nil {
		logger.Fatalf("Failed to connect to Kosmi: %v", err)
	}

	logger.Info("Successfully connected to Kosmi!")

	// Start message listener
	go func() {
		for msg := range cfg.Remote {
			logger.Infof("Received message: [%s] %s: %s", 
				msg.Timestamp.Format("15:04:05"), 
				msg.Username, 
				msg.Text)
		}
	}()

	// Wait for interrupt signal
	logger.Info("Listening for messages... Press Ctrl+C to exit")
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// Optional: Send a test message after 5 seconds
	go func() {
		time.Sleep(5 * time.Second)
		logger.Info("Bridge is running. Messages from Kosmi will appear above.")
		logger.Info("To test sending messages, integrate with IRC or use the full Matterbridge setup")
	}()

	<-sigChan
	logger.Info("Shutting down...")

	// Disconnect
	if err := b.Disconnect(); err != nil {
		logger.Errorf("Error disconnecting: %v", err)
	}

	logger.Info("Goodbye!")
}

