package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/toki/oto/services/core/internal/httpserver"
)

func main() {
	addr := os.Getenv("OTO_CORE_ADDR")
	if addr == "" {
		addr = "127.0.0.1:8080"
	}

	log.Printf("Starting OTO Core server on %s", addr)
	server := httpserver.NewServer(addr)
	runnerSocketAddr := os.Getenv("OTO_RUNNER_SOCKET_ADDR")
	if runnerSocketAddr == "" {
		runnerSocketAddr = "127.0.0.1:18080"
	}
	server.EnableRunnerSocket(runnerSocketAddr)
	log.Printf("Starting OTO runner proto-socket listener on %s", runnerSocketAddr)

	// Channel to listen for errors from the server run
	serverError := make(chan error, 1)

	go func() {
		if err := server.Start(); err != nil {
			serverError <- err
		}
	}()

	// Channel to listen for interrupt signals
	shutdownSignal := make(chan os.Signal, 1)
	signal.Notify(shutdownSignal, os.Interrupt, syscall.SIGTERM)

	select {
	case err := <-serverError:
		log.Fatalf("Server error: %v", err)
	case <-shutdownSignal:
		log.Println("Shutting down server gracefully...")

		// Set a timeout context for graceful shutdown
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()

		if err := server.Shutdown(ctx); err != nil {
			log.Printf("Error during graceful shutdown: %v", err)
			os.Exit(1)
		}
		log.Println("Server stopped")
	}
}
