package knowledge

import (
	"crypto/sha256"
	"encoding/hex"
	"reflect"
	"testing"
)

func TestContentHash(t *testing.T) {
	t.Run("determinism", func(t *testing.T) {
		a := contentHash("hello")
		b := contentHash("hello")
		if a != b {
			t.Errorf("contentHash not deterministic: %q != %q", a, b)
		}
	})

	t.Run("empty string known sha256", func(t *testing.T) {
		got := contentHash("")
		h := sha256.Sum256([]byte(""))
		want := hex.EncodeToString(h[:])
		if got != want {
			t.Errorf("contentHash(\"\") = %q, want %q", got, want)
		}
	})

	t.Run("different inputs different outputs", func(t *testing.T) {
		if contentHash("a") == contentHash("b") {
			t.Error("different inputs produced same hash")
		}
	})

	t.Run("output is 64-char hex", func(t *testing.T) {
		got := contentHash("anything")
		if len(got) != 64 {
			t.Errorf("len = %d, want 64", len(got))
		}
		for _, r := range got {
			isHex := (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f')
			if !isHex {
				t.Errorf("non-hex char %q in hash %q", r, got)
				break
			}
		}
	})
}

func TestStr(t *testing.T) {
	cases := []struct {
		name string
		m    map[string]any
		key  string
		want string
	}{
		{"missing key", map[string]any{}, "nope", ""},
		{"string value", map[string]any{"k": "v"}, "k", "v"},
		{"int value", map[string]any{"k": 42}, "k", ""},
		{"nil value", map[string]any{"k": nil}, "k", ""},
		{"empty string", map[string]any{"k": ""}, "k", ""},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got := str(c.m, c.key)
			if got != c.want {
				t.Errorf("str() = %q, want %q", got, c.want)
			}
		})
	}
}

func TestStrSlice(t *testing.T) {
	cases := []struct {
		name string
		m    map[string]any
		key  string
		want []string
	}{
		{"missing key", map[string]any{}, "tags", nil},
		{"all strings", map[string]any{"tags": []any{"a", "b", "c"}}, "tags", []string{"a", "b", "c"}},
		{"mixed types", map[string]any{"tags": []any{1, "a", true, "b"}}, "tags", []string{"a", "b"}},
		{"empty array", map[string]any{"tags": []any{}}, "tags", []string{}},
		{"nil elements filtered", map[string]any{"tags": []any{nil, "a", nil, "b"}}, "tags", []string{"a", "b"}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got := strSlice(c.m, c.key)
			if len(got) != len(c.want) {
				t.Errorf("len = %d, want %d (got %v)", len(got), len(c.want), got)
				return
			}
			for i := range got {
				if got[i] != c.want[i] {
					t.Errorf("[%d] = %q, want %q", i, got[i], c.want[i])
				}
			}
		})
	}
}

func TestMapVal(t *testing.T) {
	cases := []struct {
		name string
		m    map[string]any
		key  string
		want map[string]any
	}{
		{"missing key", map[string]any{}, "nope", nil},
		{"present map", map[string]any{"k": map[string]any{"x": 1}}, "k", map[string]any{"x": 1}},
		{"wrong type string", map[string]any{"k": "v"}, "k", nil},
		{"nested map", map[string]any{"k": map[string]any{"a": map[string]any{"b": 2}}}, "k", map[string]any{"a": map[string]any{"b": 2}}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got := mapVal(c.m, c.key)
			if !reflect.DeepEqual(got, c.want) {
				t.Errorf("mapVal() = %v, want %v", got, c.want)
			}
		})
	}
}

func TestToPGArray(t *testing.T) {
	cases := []struct {
		name string
		tags []string
		want string
	}{
		{"empty", []string{}, "{}"},
		{"single", []string{"a"}, `{"a"}`},
		{"multiple", []string{"a", "b"}, `{"a","b"}`},
		{"nil", nil, "{}"},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got := toPGArray(c.tags)
			if got != c.want {
				t.Errorf("toPGArray() = %q, want %q", got, c.want)
			}
		})
	}

	// Special chars: tags containing " or \ are NOT escaped by toPGArray.
	// This is a latent bug — Postgres array literals require these to be
	// backslash-escaped. Test documents current behavior so a fix is
	// detectable. Should be fixed.
	t.Run("special chars unescaped (current buggy behavior)", func(t *testing.T) {
		got := toPGArray([]string{`a"b`, `c\d`})
		// Current output: {"a"b","c\d"} — invalid Postgres array literal.
		want := `{"a"b","c\d"}`
		if got != want {
			t.Errorf("toPGArray(special) = %q, want %q (if this changed, the escaping bug was fixed — update this test)", got, want)
		}
	})
}
