package main

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

	"github.com/sorti/openspeak/internal/auth"
	"github.com/sorti/openspeak/internal/channel"
	"github.com/sorti/openspeak/internal/grpc"
	"github.com/sorti/openspeak/internal/logger"
	"github.com/sorti/openspeak/internal/presence"
	"github.com/sorti/openspeak/internal/voice"
)

func main() {
	port := flag.Int("port", 50051, "gRPC server port")
	logLevel := flag.String("log-level", "info", "Log level (debug, info, warn, error)")
	flag.Parse()

	// Setup logger
	log := logger.NewFromString(*logLevel)
	log.Info(fmt.Sprintf("Starting OpenSpeak server on port %d", *port))

	// Initialize managers
	tokenManager := auth.NewTokenManager()
	channelManager := channel.NewManager()
	presenceManager := presence.NewManager()
	voiceRouter := voice.NewRouter()

	// Add a default admin token for testing
	adminToken, err := auth.GenerateToken()
	if err != nil {
		log.Fatal("Failed to generate admin token:", err)
	}
	tokenManager.AddToken(adminToken, "admin", []string{"admin"})
	log.Info(fmt.Sprintf("Admin token: %s", adminToken))

	// Create gRPC server
	grpcServer, err := grpc.NewServer(*port, log, tokenManager, channelManager, presenceManager, voiceRouter)
	if err != nil {
		log.Fatal("Failed to create gRPC server:", err)
	}

	// Start server in background
	go func() {
		if err := grpcServer.Start(); err != nil {
			log.Fatal("Failed to start gRPC server:", err)
		}
	}()

	// Wait for shutdown signal
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	sig := <-sigChan
	log.Info(fmt.Sprintf("Received signal: %v", sig))

	// Stop server
	grpcServer.Stop()
	log.Info("Server stopped")
}
