package main

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

	"github.com/markdown-editor/internal/api"
	"github.com/markdown-editor/pkg/logger"
	"github.com/spf13/cobra"
)

var (
	dataDir string
	host    string
	port    int
)

func main() {
	rootCmd := &cobra.Command{
		Use:   "server",
		Short: "Markdown Editor Server",
		Run:   runServer,
	}

	rootCmd.Flags().StringVar(&dataDir, "data-dir", "./data", "Storage path for markdown files")
	rootCmd.Flags().StringVar(&host, "host", "127.0.0.1", "Bind address")
	rootCmd.Flags().IntVar(&port, "port", 8080, "Server port")

	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func runServer(cmd *cobra.Command, args []string) {
	// Initialize logger
	logger.Init()

	logger.Info("Starting Markdown Editor Server")
	logger.Infof("Data directory: %s", dataDir)
	logger.Infof("Server will bind to %s:%d", host, port)

	// Initialize API server
	svr, err := api.NewServer(dataDir, host, port)
	if err != nil {
		logger.Fatalf("Failed to initialize server: %v", err)
	}

	// Setup signal handling for graceful shutdown
	ctx, cancel := signal.NotifyContext(cmd.Context(), syscall.SIGINT, syscall.SIGTERM)
	defer cancel()

	// Start server in a goroutine
	errChan := make(chan error, 1)
	go func() {
		logger.Infof("Server listening on %s:%d", host, port)
		errChan <- svr.Start()
	}()

	// Wait for shutdown signal or error
	select {
	case <-ctx.Done():
		logger.Info("Shutdown signal received")
	case err := <-errChan:
		if err != nil {
			logger.Fatalf("Server error: %v", err)
		}
	}

	logger.Info("Server stopped gracefully")
}
