package output

import (
	"bytes"
	"io"
	"os"
	"regexp"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/salvacybersec/keyhunter/pkg/engine"
)

// ansiRE strips lipgloss/ANSI color escape sequences so assertions can run
// against plain text regardless of the terminal styling applied at render time.
var ansiRE = regexp.MustCompile(`\x1b\[[0-9;]*m`)

func stripANSI(s string) string { return ansiRE.ReplaceAllString(s, "") }

// captureStdout redirects os.Stdout for the duration of fn and returns the
// captured bytes (ANSI-stripped for convenience). Used by legacy PrintFindings
// tests that still target stdout for backward compatibility.
func captureStdout(t *testing.T, fn func()) string {
	t.Helper()
	orig := os.Stdout
	r, w, err := os.Pipe()
	require.NoError(t, err)
	os.Stdout = w

	done := make(chan struct{})
	var buf bytes.Buffer
	go func() {
		_, _ = io.Copy(&buf, r)
		close(done)
	}()

	fn()

	require.NoError(t, w.Close())
	os.Stdout = orig
	<-done
	return stripANSI(buf.String())
}

// --- Legacy PrintFindings wrapper tests (kept for backward compatibility) ---

func TestPrintFindings_NoVerification_Unchanged(t *testing.T) {
	findings := []engine.Finding{
		{
			ProviderName: "openai",
			KeyValue:     "sk-test-1234567890abcdef",
			KeyMasked:    "sk-test-...cdef",
			Confidence:   "high",
			Source:       "main.go",
			LineNumber:   42,
		},
	}
	out := captureStdout(t, func() { PrintFindings(findings, false) })
	assert.NotContains(t, out, "VERIFY", "VERIFY column must not appear when no findings are verified")
	assert.Contains(t, out, "PROVIDER")
	assert.Contains(t, out, "openai")
}

func TestPrintFindings_LiveVerification_ShowsCheck(t *testing.T) {
	findings := []engine.Finding{
		{
			ProviderName: "openai",
			KeyMasked:    "sk-test-...cdef",
			Confidence:   "high",
			Source:       "main.go",
			LineNumber:   42,
			Verified:     true,
			VerifyStatus: "live",
		},
	}
	out := captureStdout(t, func() { PrintFindings(findings, false) })
	assert.Contains(t, out, "VERIFY")
	assert.Contains(t, out, "live")
}

func TestPrintFindings_Metadata_Rendered(t *testing.T) {
	findings := []engine.Finding{
		{
			ProviderName:   "openai",
			KeyMasked:      "sk-test-...cdef",
			Confidence:     "high",
			Source:         "main.go",
			LineNumber:     42,
			Verified:       true,
			VerifyStatus:   "live",
			VerifyMetadata: map[string]string{"org": "Acme", "tier": "plus"},
		},
	}
	out := captureStdout(t, func() { PrintFindings(findings, false) })
	assert.Contains(t, out, "org: Acme")
	assert.Contains(t, out, "tier: plus")
	orgIdx := strings.Index(out, "org: Acme")
	tierIdx := strings.Index(out, "tier: plus")
	require.GreaterOrEqual(t, orgIdx, 0)
	require.GreaterOrEqual(t, tierIdx, 0)
	assert.Less(t, orgIdx, tierIdx, "metadata pairs should be sorted alphabetically")
}

// --- New TableFormatter tests ---

func TestTableFormatter_Empty(t *testing.T) {
	var buf bytes.Buffer
	require.NoError(t, TableFormatter{}.Format(nil, &buf, Options{}))
	assert.Equal(t, "No API keys found.\n", buf.String())
}

func TestTableFormatter_NoColorInBuffer(t *testing.T) {
	// bytes.Buffer is not a TTY, so ColorsEnabled should return false and no
	// ANSI escape sequences should be present in the output.
	findings := []engine.Finding{
		{
			ProviderName: "openai",
			KeyMasked:    "sk-test-...cdef",
			Confidence:   "high",
			Source:       "main.go",
			LineNumber:   1,
		},
		{
			ProviderName: "anthropic",
			KeyMasked:    "sk-ant-...beef",
			Confidence:   "medium",
			Source:       "main.go",
			LineNumber:   2,
			Verified:     true,
			VerifyStatus: "live",
		},
	}
	var buf bytes.Buffer
	require.NoError(t, TableFormatter{}.Format(findings, &buf, Options{}))
	assert.NotContains(t, buf.String(), "\x1b[", "non-TTY writer must not receive ANSI escape codes")
	assert.Contains(t, buf.String(), "VERIFY")
	assert.Contains(t, buf.String(), "2 key(s) found.")
}

func TestTableFormatter_UnverifiedLayout(t *testing.T) {
	findings := []engine.Finding{
		{ProviderName: "openai", KeyMasked: "x", Confidence: "low", Source: "s", LineNumber: 1},
	}
	var buf bytes.Buffer
	require.NoError(t, TableFormatter{}.Format(findings, &buf, Options{}))
	// First line is the header.
	header := strings.SplitN(buf.String(), "\n", 2)[0]
	assert.NotContains(t, header, "VERIFY")
}

func TestTableFormatter_VerifiedLayout(t *testing.T) {
	findings := []engine.Finding{
		{
			ProviderName: "openai", KeyMasked: "x", Confidence: "high",
			Source: "s", LineNumber: 1, Verified: true, VerifyStatus: "live",
		},
	}
	var buf bytes.Buffer
	require.NoError(t, TableFormatter{}.Format(findings, &buf, Options{}))
	header := strings.SplitN(buf.String(), "\n", 2)[0]
	assert.Contains(t, header, "VERIFY")
	assert.Contains(t, buf.String(), "live")
}

func TestTableFormatter_Masking(t *testing.T) {
	findings := []engine.Finding{
		{
			ProviderName: "openai",
			KeyValue:     "sk-FULL-SECRET-VALUE",
			KeyMasked:    "sk-FULL-...ALUE",
			Confidence:   "high",
			Source:       "s",
			LineNumber:   1,
		},
	}

	var masked bytes.Buffer
	require.NoError(t, TableFormatter{}.Format(findings, &masked, Options{Unmask: false}))
	assert.Contains(t, masked.String(), "sk-FULL-...ALUE")
	assert.NotContains(t, masked.String(), "sk-FULL-SECRET-VALUE")

	var unmasked bytes.Buffer
	require.NoError(t, TableFormatter{}.Format(findings, &unmasked, Options{Unmask: true}))
	assert.Contains(t, unmasked.String(), "sk-FULL-SECRET-VALUE")
}

func TestTableFormatter_MetadataSorted(t *testing.T) {
	findings := []engine.Finding{
		{
			ProviderName:   "openai",
			KeyMasked:      "x",
			Confidence:     "high",
			Source:         "s",
			LineNumber:     1,
			Verified:       true,
			VerifyStatus:   "live",
			VerifyMetadata: map[string]string{"z": "1", "a": "2"},
		},
	}
	var buf bytes.Buffer
	require.NoError(t, TableFormatter{}.Format(findings, &buf, Options{}))
	out := buf.String()
	aIdx := strings.Index(out, "a: 2")
	zIdx := strings.Index(out, "z: 1")
	require.GreaterOrEqual(t, aIdx, 0)
	require.GreaterOrEqual(t, zIdx, 0)
	assert.Less(t, aIdx, zIdx)
}

func TestTableFormatter_RegisteredUnderTable(t *testing.T) {
	f, err := Get("table")
	require.NoError(t, err)
	_, ok := f.(TableFormatter)
	assert.True(t, ok, "the \"table\" registry entry must be a TableFormatter")
}
