package main

import (
	"os"
	"testing"
)

// TestIsCharDeviceRejectsNonConsoles pins down the half of the check that can
// be tested without a terminal: a pipe, a regular file and a closed handle
// must all read as "not a console", because each of them means something other
// than a person waiting at a keyboard.
//
// Getting this wrong in this direction is the dangerous one: it would drop a
// script or a build pipeline into an interactive prompt and hang it forever.
func TestIsCharDeviceRejectsNonConsoles(t *testing.T) {
	r, w, err := os.Pipe()
	if err != nil {
		t.Fatalf("pipe: %v", err)
	}
	defer r.Close()
	defer w.Close()

	tmp, err := os.CreateTemp(t.TempDir(), "out")
	if err != nil {
		t.Fatalf("temp file: %v", err)
	}
	defer tmp.Close()

	devNull, err := os.Open(os.DevNull)
	if err != nil {
		t.Fatalf("open %s: %v", os.DevNull, err)
	}
	defer devNull.Close()

	for _, tc := range []struct {
		name string
		file *os.File
		want bool
	}{
		{"read end of a pipe", r, false},
		{"write end of a pipe", w, false},
		{"regular file", tmp, false},
		// os.DevNull IS a character device on Unix, so this case documents a
		// real limitation rather than asserting a value that differs by
		// platform: `prog < /dev/null` on Unix looks interactive on stdin.
		// It is harmless, because stdout must ALSO be a console, and a script
		// redirecting stdin almost always redirects stdout too.
	} {
		if got := isCharDevice(tc.file); got != tc.want {
			t.Errorf("isCharDevice(%s) = %v, want %v", tc.name, got, tc.want)
		}
	}
	_ = devNull
}

// TestIsCharDeviceHandlesAClosedFile makes sure a handle we cannot stat is
// treated as "not a console" rather than panicking or defaulting to true.
func TestIsCharDeviceHandlesAClosedFile(t *testing.T) {
	f, err := os.CreateTemp(t.TempDir(), "closed")
	if err != nil {
		t.Fatalf("temp file: %v", err)
	}
	f.Close()
	if isCharDevice(f) {
		t.Error("isCharDevice(closed file) = true, want false")
	}
}

// TestInteractiveConsoleNeedsBothEnds asserts the AND: one console end is not
// enough. Under `go test` stdout is not a terminal, so this must be false.
func TestInteractiveConsoleNeedsBothEnds(t *testing.T) {
	if interactiveConsole() {
		t.Error("interactiveConsole() = true under `go test`, where output is captured; " +
			"the guided prompt would hang any non-interactive run")
	}
}

// TestGuidedConfigIsQuickAndWritesNothing guards what guided mode offers in
// place of a folder default: a measurement budget. Somebody who double-clicked
// the program is watching a window, so it has to be over in seconds — and the
// disk test, the only part of this program that writes anything at all, must be
// off unless the reader asks for it by name.
func TestGuidedConfigIsQuickAndWritesNothing(t *testing.T) {
	cfg := guidedConfig("")

	if cfg.diskDir != "" {
		t.Errorf("guidedConfig(\"\").diskDir = %q, want empty: the default guided run must not write anywhere", cfg.diskDir)
	}
	if cfg.seconds <= 0 || cfg.seconds > 2 {
		t.Errorf("guidedConfig().seconds = %g, want a short budget in (0, 2]", cfg.seconds)
	}
	// Four subsystems plus the untimed warm-up: the whole guided run has to
	// stay inside the few seconds a reader will sit through.
	if total := 4*cfg.seconds + warmupMs/1000.0; total > 10 {
		t.Errorf("a guided run would take about %gs, which is too long to watch", total)
	}

	// The budget still has to be one the program itself would accept, or the
	// guided path would be measuring on settings the CLI rejects.
	if cfg.seconds > maxSeconds {
		t.Errorf("guidedConfig().seconds = %g exceeds maxSeconds %g", cfg.seconds, maxSeconds)
	}
	if cfg.memBufMiB < memMinMiB || cfg.memBufMiB > memMaxMiB {
		t.Errorf("guidedConfig().memBufMiB = %d, outside the accepted range %d..%d", cfg.memBufMiB, memMinMiB, memMaxMiB)
	}
	if cfg.diskCapMiB < diskMinMiB || cfg.diskCapMiB > diskMaxMiB {
		t.Errorf("guidedConfig().diskCapMiB = %d, outside the accepted range %d..%d", cfg.diskCapMiB, diskMinMiB, diskMaxMiB)
	}

	// When the reader does name a folder, it is the one that gets used.
	if got := guidedConfig("/tmp/somewhere").diskDir; got != "/tmp/somewhere" {
		t.Errorf("guidedConfig(dir).diskDir = %q, want the folder the reader gave", got)
	}
}
