package main

import (
	"fmt"
	"os"

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

var rootCmd = &cobra.Command{
	Use:   "markdown-editor",
	Short: "A WYSIWYG Markdown Editor",
	Long:  `A WYSIWYG Markdown Editor with Go backend and React frontend`,
}

var dataDir string
var port int
var host string

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

func main() {
	log := logger.NewLogger()
	log.Info("Starting markdown editor server")

	rootCmd.Run = func(cmd *cobra.Command, args []string) {
		// Initialize API
		apiHandler := api.NewAPIHandler(dataDir, log)

		// Create server
		srv := server.NewServer(host, port, apiHandler, log)

		// Start server
		log.Infof("Server starting on %s:%d", host, port)
		if err := srv.Start(); err != nil {
			log.Errorf("Server failed: %v", err)
			os.Exit(1)
		}
	}

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