package main

import (
	"fmt"
	"log"

	"mengyamonitor-backend-server/internal/config"
	"mengyamonitor-backend-server/internal/grpcrun"
	"mengyamonitor-backend-server/internal/hub"
	"mengyamonitor-backend-server/internal/ingest"
	"mengyamonitor-backend-server/internal/router"
	"mengyamonitor-backend-server/internal/store"
)

func main() {
	cfg := config.Load()
	st, err := store.Open(cfg.DBPath)
	if err != nil {
		log.Fatalf("store: %v", err)
	}
	defer st.Close()

	metricsHub := hub.New()
	ingestSrv := &ingest.Server{Store: st, Hub: metricsHub}

	grpcAddr := fmt.Sprintf("%s:%s", cfg.Host, cfg.GRPCPort)
	go func() {
		log.Printf("gRPC AgentIngest listening on %s", grpcAddr)
		if err := grpcrun.Serve(grpcAddr, ingestSrv); err != nil {
			log.Fatalf("grpc: %v", err)
		}
	}()

	httpAddr := fmt.Sprintf("%s:%s", cfg.Host, cfg.Port)
	log.Printf("central HTTP/WS on http://%s", httpAddr)
	if err := router.New(cfg, st, metricsHub).Run(httpAddr); err != nil {
		log.Fatalf("http: %v", err)
	}
}
