package main

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

	"spektr/internal/config"
	"spektr/internal/discovery"
	grpcserver "spektr/internal/grpc"
	"spektr/internal/service"
	"spektr/internal/uart"
)

func main() {
	configPath := flag.String("config", "./config.yaml", "path to config file")
	flag.Parse()

	cfg, err := config.Load(*configPath)
	if err != nil {
		log.Fatal(err)
	}

	u, err := uart.New(cfg.UARTDevice, cfg.UARTBaud)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("UART opened: %s @ %d", cfg.UARTDevice, cfg.UARTBaud)
	defer u.Close()

	svc := service.New(u)
	ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer cancel()

	go func() {
		if err := discovery.Serve(ctx, cfg.DiscoveryPort, cfg.GRPCAdvertiseAddr); err != nil {
			log.Println("discovery stopped:", err)
		}
	}()

	if err := grpcserver.Serve(ctx, cfg.GRPCListenAddr, svc); err != nil {
		log.Fatal(err)
	}
}
