package main

import (
	"testing"

	apppkg "github.com/jan/fm-rds-tx/internal/app"
	cfgpkg "github.com/jan/fm-rds-tx/internal/config"
	"github.com/jan/fm-rds-tx/internal/output"
	"github.com/jan/fm-rds-tx/internal/platform"
)

func TestIngestEnabled(t *testing.T) {
	tests := []struct {
		name string
		kind string
		want bool
	}{
		{name: "empty", kind: "", want: false},
		{name: "none", kind: "none", want: false},
		{name: "none uppercase and spaces", kind: "  NONE  ", want: false},
		{name: "stdin", kind: "stdin", want: true},
		{name: "http raw uppercase", kind: " HTTP-RAW ", want: true},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			if got := ingestEnabled(tc.kind); got != tc.want {
				t.Fatalf("ingestEnabled(%q)=%v want %v", tc.kind, got, tc.want)
			}
		})
	}
}

func TestTxBridgeExportsQueueStats(t *testing.T) {
	cfg := cfgpkg.Default()
	driver := platform.NewSimulatedDriver(nil)
	engine := apppkg.NewEngine(cfg, driver)
	bridge := &txBridge{engine: engine}
	stats := bridge.TXStats()

	raw, ok := stats["queue"]
	if !ok {
		t.Fatalf("expected queue stats in tx stats")
	}

	queue, ok := raw.(output.QueueStats)
	if !ok {
		t.Fatalf("queue stats type mismatch: %T", raw)
	}

	if queue.Capacity != cfg.Runtime.FrameQueueCapacity {
		t.Fatalf("unexpected queue capacity: want %d got %d", cfg.Runtime.FrameQueueCapacity, queue.Capacity)
	}

	if queue.Health != output.QueueHealthCritical {
		t.Fatalf("queue health should be critical with empty queue, got %s", queue.Health)
	}

	indicatorRaw, ok := stats["runtimeIndicator"]
	if !ok {
		t.Fatalf("expected runtimeIndicator in tx stats")
	}
	indicator, ok := indicatorRaw.(apppkg.RuntimeIndicator)
	if !ok {
		t.Fatalf("runtimeIndicator type mismatch: %T", indicatorRaw)
	}
	if indicator != apppkg.RuntimeIndicatorQueueCritical {
		t.Fatalf("runtime indicator should be queueCritical, got %s", indicator)
	}
	freqRaw, ok := stats["appliedFrequencyMHz"]
	if !ok {
		t.Fatalf("missing appliedFrequencyMHz")
	}
	freq, ok := freqRaw.(float64)
	if !ok {
		t.Fatalf("appliedFrequencyMHz type mismatch: %T", freqRaw)
	}
	if freq != cfg.FM.FrequencyMHz {
		t.Fatalf("applied frequency mismatch: want %v got %v", cfg.FM.FrequencyMHz, freq)
	}
	if historyRaw, ok := stats["faultHistory"]; !ok {
		t.Fatalf("expected faultHistory in tx stats")
	} else if history, ok := historyRaw.([]apppkg.FaultEvent); !ok {
		t.Fatalf("faultHistory type mismatch: %T", historyRaw)
	} else if len(history) != 0 {
		t.Fatalf("expected no faults yet, got %d", len(history))
	}
}
