package geminicli

import (
	"strings"
	"testing"

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

func TestIsBase64Char(t *testing.T) {
	tests := []struct {
		char byte
		want bool
	}{
		{'A', true}, {'Z', true},
		{'a', true}, {'z', true},
		{'0', true}, {'9', true},
		{'+', true}, {'/', true}, {'=', true},
		{'-', false}, {'_', false}, {' ', false},
		{'.', false}, {'\n', false},
	}

	for _, tt := range tests {
		t.Run(string(tt.char), func(t *testing.T) {
			got := isBase64Char(tt.char)
			require.Equal(t, tt.want, got)
		})
	}
}

func TestTruncateBase64InMessage(t *testing.T) {
	tests := []struct {
		name string
		msg  string
		want string
	}{
		{
			name: "no_base64",
			msg:  "This is a normal message without base64",
			want: "This is a normal message without base64",
		},
		{
			name: "short_base64",
			msg:  "data:image/png;base64,abc123",
			want: "data:image/png;base64,abc123",
		},
		{
			name: "long_base64_truncated",
			msg:  "data:image/png;base64," + strings.Repeat("a", 100),
			want: "data:image/png;base64," + strings.Repeat("a", 50) + "...[truncated]",
		},
		{
			name: "multiple_base64",
			msg:  "start;base64," + strings.Repeat("b", 30) + " middle;base64," + strings.Repeat("c", 60),
			want: "start;base64," + strings.Repeat("b", 30) + " middle;base64," + strings.Repeat("c", 50) + "...[truncated]",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := truncateBase64InMessage(tt.msg)
			require.Equal(t, tt.want, got)
		})
	}
}

func TestSanitizeBodyForLogs(t *testing.T) {
	tests := []struct {
		name string
		body string
		check func(t *testing.T, got string)
	}{
		{
			name: "short_body_no_change",
			body: "Short message",
			check: func(t *testing.T, got string) {
				require.Equal(t, "Short message", got)
			},
		},
		{
			name: "body_truncated",
			body: strings.Repeat("x", 3000),
			check: func(t *testing.T, got string) {
				require.LessOrEqual(t, len(got), 2100) // maxLogBodyLen + "...[truncated]"
				require.True(t, strings.HasSuffix(got, "...[truncated]"))
			},
		},
		{
			name: "body_with_base64_truncated",
			body: "data:image/png;base64," + strings.Repeat("a", 100),
			check: func(t *testing.T, got string) {
				require.Contains(t, got, "...[truncated]")
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := SanitizeBodyForLogs(tt.body)
			tt.check(t, got)
		})
	}
}
