package main

import (
	"context"

	"github.com/urfave/cli/v3"

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

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

type meshCoreConfig struct {
	Broker   hamview.BrokerConfig   `yaml:"broker"`
	Receiver hamview.MeshCoreConfig `yaml:"receiver"`
	Include  []string               `yaml:"include"`
}

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

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

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

	receiver, err := hamview.NewMeshCoreReceiver(&config.Receiver)
	if err != nil {
		return err
	}
	defer receiver.Close()

	info := receiver.Info() // TODO: enrich info from config?
	if err = broker.StartRadio(protocol.MeshCore, info); err != nil {
		logger.Fatalf("receiver: can't start broker: %v", err)
		return err
	}

	// Trace scheduler
	//go receiver.RunTraces()

	// Packet decoder
	go func() {
		logger.Info("receiver: start receiving packets")
		for packet := range receiver.RawPackets() {
			if len(packet.Raw) >= 1 {
				var (
					header      = packet.Raw[0]
					version     = (header >> 6) & 0x03
					routeType   = meshcore.RouteType(header & 0x03)
					payloadType = meshcore.PayloadType((header >> 2) & 0x0F)
				)
				logger.Debugf("meshcore packet: %d %s %s: %d bytes",
					version,
					routeType,
					payloadType,
					len(packet.Raw))
			}
			if err = broker.PublishPacket("meshcore/packet", packet); err != nil {
				logger.Errorf("receiver: failed to publish packet: %v", err)
			}
		}
		logger.Warn("receiver: closing")
	}()

	return waitForInterrupt()
}
