package style

import (
	"bytes"
	"os"
	"strings"
	"testing"
)

// TestStyleNoOpsForNonTTYWriter pins that styled helpers don't emit
// ANSI escapes when the destination isn't a terminal. Buffers stand
// in for any non-TTY writer (CI, redirected stdout, log files).
func TestStyleNoOpsForNonTTYWriter(t *testing.T) {
	var buf bytes.Buffer
	cases := map[string]string{
		"pass": Pass(&buf, "ok"),
		"fail": Fail(&buf, "boom"),
		"warn": Warn(&buf, "huh"),
		"dim":  Dim(&buf, "sub"),
		"bold": Bold(&buf, "bold"),
	}
	for label, got := range cases {
		if strings.Contains(got, "\x1b[") {
			t.Errorf("%s: contains ANSI escape on non-TTY writer: %q", label, got)
		}
	}
}

// TestStyleSuppressedByNoColor pins https://no-color.org compliance:
// even on a "real" TTY, NO_COLOR forces plain output.
func TestStyleSuppressedByNoColor(t *testing.T) {
	t.Setenv("NO_COLOR", "1")
	r, w, err := os.Pipe()
	if err != nil {
		t.Fatalf("Pipe: %v", err)
	}
	defer r.Close()
	defer w.Close()
	// w is a pipe end, not a char device — NO_COLOR is the dominant
	// gate but verifying the helper still suppresses guards against
	// a future TTY-detection regression that would otherwise need a
	// pty harness to surface.
	if got := Pass(w, "ok"); strings.Contains(got, "\x1b[") {
		t.Errorf("NO_COLOR set but Pass() emitted ANSI: %q", got)
	}
	if got := Fail(w, "boom"); strings.Contains(got, "\x1b[") {
		t.Errorf("NO_COLOR set but Fail() emitted ANSI: %q", got)
	}
}

// TestSupportsColorRespectsNoColor confirms the gate function used
// by the helpers. Required for callers that compose multi-segment
// strings and want to ask once.
func TestSupportsColorRespectsNoColor(t *testing.T) {
	t.Setenv("NO_COLOR", "1")
	tmp, err := os.CreateTemp(t.TempDir(), "style-*")
	if err != nil {
		t.Fatalf("CreateTemp: %v", err)
	}
	defer tmp.Close()
	if SupportsColor(tmp) {
		t.Fatal("SupportsColor returned true with NO_COLOR set")
	}
}
