package engine

import (
	"testing"

	"git.difuse.io/Difuse/Mellaris/analyzer"
)

type namedAnalyzer struct{ name string }

func (a namedAnalyzer) Name() string { return a.name }
func (a namedAnalyzer) Limit() int   { return 0 }

func TestSignatureSelectorTCPPrunesByPayloadNotPort(t *testing.T) {
	sel := newAnalyzerSelector(AnalyzerSelectionModeSignature, &statsCounters{})
	all := []analyzer.Analyzer{
		namedAnalyzer{"http"},
		namedAnalyzer{"tls"},
		namedAnalyzer{"trojan"},
		namedAnalyzer{"ssh"},
		namedAnalyzer{"socks"},
		namedAnalyzer{"fet"},
	}
	// TLS record-like prefix, regardless of destination port.
	payload := []byte{0x16, 0x03, 0x03, 0x00, 0x10}
	selected := sel.SelectTCP(all, payload)

	got := make(map[string]bool)
	for _, a := range selected {
		got[a.Name()] = true
	}
	for _, keep := range []string{"tls", "trojan", "fet"} {
		if !got[keep] {
			t.Fatalf("expected analyzer %q to be selected", keep)
		}
	}
	for _, drop := range []string{"http", "ssh", "socks"} {
		if got[drop] {
			t.Fatalf("expected analyzer %q to be pruned", drop)
		}
	}
}

func TestSignatureSelectorConservativeFallback(t *testing.T) {
	sel := newAnalyzerSelector(AnalyzerSelectionModeSignature, &statsCounters{})
	all := []analyzer.Analyzer{
		namedAnalyzer{"http"},
		namedAnalyzer{"tls"},
		namedAnalyzer{"custom"},
	}
	payload := []byte{0xde, 0xad, 0xbe, 0xef}
	selected := sel.SelectTCP(all, payload)
	if len(selected) != len(all) {
		t.Fatalf("expected conservative fallback to keep all analyzers, got=%d want=%d", len(selected), len(all))
	}
}
