package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
	"weatherstation/internal/fusion"
	"weatherstation/internal/server"
)

func main() {
	server.SetupLogger()

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	go func() {
		for {
			if ctx.Err() != nil {
				return
			}
			now := time.Now()
			next := now.Truncate(time.Hour).Add(time.Hour).Add(5 * time.Minute)
			sleep := time.Until(next)
			if sleep < 0 {
				sleep = 0
			}
			t := time.NewTimer(sleep)
			select {
			case <-ctx.Done():
				t.Stop()
				return
			case <-t.C:
			}

			issued := next.Truncate(time.Hour)
			if err := fusion.RunForIssued(context.Background(), issued); err != nil {
				log.Printf("[service-fusion] run failed: %v", err)
			} else {
				log.Printf("[service-fusion] completed issued=%s", issued.Format("2006-01-02 15:04:05"))
			}
		}
	}()

	<-ctx.Done()
	log.Println("service-fusion shutting down")
}
