package main

import (
	"context"
	"log"
	"os"

	"github.com/sirupsen/logrus"
	"github.com/urfave/cli/v3"

	"git.maze.io/go/ham/protocol"

	"git.maze.io/ham/hamview"
	"git.maze.io/ham/hamview/internal/cmd"
)

var logger *logrus.Logger

func init() {
	logger = cmd.NewLogger(nil)
}

func main() {
	cmd := &cli.Command{
		Name:   "hamview-collector",
		Usage:  "Collector for HAM radio protocols",
		Action: run,
		Before: cmd.ConfigureLogging(&logger),
		Flags:  cmd.AllFlags("hamview-collector.yaml"),
	}

	if err := cmd.Run(context.Background(), os.Args); err != nil {
		log.Fatal(err)
	}
}

type collectorConfig struct {
	hamview.CollectorConfig `yaml:",inline"`
	Broker                  hamview.BrokerConfig `yaml:"broker"`
	Include                 []string             `yaml:"include"`
	MeshCore                struct {
		Group meshCoreGroupConfig `yaml:"group"`
	} `yaml:"meshcore"`
}

func (config *collectorConfig) Includes() []string {
	includes := config.Include
	config.Include = nil
	return includes
}

type meshCoreGroupConfig struct {
	Secret map[string]string `yaml:"secret"`
	Public []string          `yaml:"public"`
}

func run(ctx context.Context, command *cli.Command) error {
	var config collectorConfig
	if err := cmd.Load(logger, command.String(cmd.FlagConfig), &config); err != nil {
		return err
	}

	collector, err := hamview.NewCollector(&config.CollectorConfig)
	if err != nil {
		return err
	}
	defer collector.Close()

	broker, err := hamview.NewBroker(&config.Broker)
	if err != nil {
		return err
	}
	if err = broker.Start(); err != nil {
		return err
	}
	defer broker.Close()

	for _, proto := range []string{
		protocol.APRS,
		protocol.MeshCore,
	} {
		go collector.Collect(broker, proto+"/packet")
	}

	return cmd.WaitForInterrupt(logger, "collector")
}
