// KEKS -- Go KEKS codec implementation
// Copyright (C) 2024-2025 Anton Rudenko <rudenko.ad@phystech.edu>
//                         Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program.  If not, see <http://www.gnu.org/licenses/>.

package keks

import (
	"bytes"
	"io"
	"math/rand"
	"reflect"
	"strings"
	"testing"
	"testing/quick"

	"go.cypherpunks.su/keks/be"
)

func TestStrEmpty(t *testing.T) {
	obj := ""
	bin := mustHexDec("C0")
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.(string)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted != obj {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestStrHelloWorld(t *testing.T) {
	obj := "hello world"
	bin := append([]byte{0xCB}, []byte("hello world")...)
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.(string)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted != obj {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestStrПриветМир(t *testing.T) {
	obj := "привет мир"
	bin := append([]byte{0xD3}, []byte("привет мир")...)
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.(string)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted != obj {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestStrLen62(t *testing.T) {
	obj := strings.Repeat("a", 62)
	bin := mustHexDec("FD01" + strings.Repeat("61", 62))
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.(string)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted != obj {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestStrLen318(t *testing.T) {
	obj := strings.Repeat("a", 62+255+1)
	bin := mustHexDec("FE0001" + strings.Repeat("61", 62+255+1))
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.(string)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted != obj {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestStrLen65853(t *testing.T) {
	obj := strings.Repeat("a", 62+255+65535+1)
	bin := mustHexDec("FF0000000000000000" + strings.Repeat("61", 62+255+65535+1))
	decoder := NewDecoderFromBytes(append(bin, Junk...), nil)
	decoded, err := decoder.Decode()
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := EncodeBuf(obj, nil)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, bin) {
		t.Fatal("encoded differs")
	}
	casted, ok := decoded.(string)
	if !ok {
		t.Fatal("failed to cast")
	}
	if casted != obj {
		t.Fatal("casted differs")
	}
	if !bytes.Equal(decoder.B, Junk) {
		t.Fatal("tail differs")
	}
}

func TestStrNullByteInUTF8(t *testing.T) {
	bin := []byte("\xC5he\x00\x01\x02")
	_, err := NewDecoderFromBytes(bin, nil).Decode()
	if err != ErrUTF8Bad {
		t.Fatal(err)
	}
}

func TestStrNullByteInUTF8AndCheckDisabled(t *testing.T) {
	bin := []byte("\xC5he\x00\x01\x02")
	_, err := NewDecoderFromBytes(bin, &DecodeOpts{DisableUTF8Check: true}).Decode()
	if err == ErrUTF8Bad {
		t.Fatal(err)
	}
}

// Here go invalid UTF-8 byte(s) strategies. We can fail in following
// ways during decoding:
// * invalid start byte -- hypothesis generates integers that will
//   satisfy that fail
// * invalid continuation byte -- we strip last byte of multibyte
//   sequences
// * unexpected end of data -- we strip the last byte of our data

func TestStrStripped2ByteInUTF8(t *testing.T) {
	// 110xxxxx 10xxxxxx(STRIPPED)
	f := func(x int) bool {
		bin := []byte{0xC1, (1 << 7) | (1 << 6) | byte(x)}
		_, err := NewDecoderFromBytes(bin, nil).Decode()
		if err != ErrUTF8Bad {
			return false
		}
		_, err = NewDecoderFromBytes(bin,
			&DecodeOpts{DisableUTF8Check: true}).Decode()
		return err == nil
	}
	if err := quick.Check(f, &quick.Config{
		Values: func(v []reflect.Value, r *rand.Rand) {
			v[0] = reflect.ValueOf(r.Intn((1 << 5) - 1))
		},
	}); err != nil {
		t.Fatal(err)
	}
}

func TestStrStripped3ByteInUTF8(t *testing.T) {
	// 1110xxxx 10xxxxxx 10xxxxxx(STRIPPED)
	f := func(x int) bool {
		bin := []byte{
			0xC2,
			(1 << 7) | (1 << 6) | (1 << 5) | byte(x>>6),
			byte((1 << 7) | (((1 << 6) - 1) & x)),
		}
		_, err := NewDecoderFromBytes(bin, nil).Decode()
		if err != ErrUTF8Bad {
			return false
		}
		_, err = NewDecoderFromBytes(bin,
			&DecodeOpts{DisableUTF8Check: true}).Decode()
		return err == nil
	}
	if err := quick.Check(f, &quick.Config{
		Values: func(v []reflect.Value, r *rand.Rand) {
			v[0] = reflect.ValueOf(r.Intn((1 << 10) - 1))
		},
	}); err != nil {
		t.Fatal(err)
	}
}

func TestStrNotEnoughData(t *testing.T) {
	bin, err := EncodeBuf("hello", nil)
	if err != nil {
		panic(err)
	}
	_, err = NewDecoderFromBytes(bin[:len(bin)-1], nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal(err)
	}
}

func TestStrNotEnoughDataForLength8(t *testing.T) {
	bin, err := EncodeBuf(strings.Repeat("f", 100), nil)
	if err != nil {
		panic(err)
	}
	_, err = NewDecoderFromBytes(bin[:len(bin)-1], nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal(err)
	}
}

func TestStrNotEnoughDataForLength16(t *testing.T) {
	bin, err := EncodeBuf(strings.Repeat("f", 318), nil)
	if err != nil {
		panic(err)
	}
	_, err = NewDecoderFromBytes(bin[:len(bin)-1], nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal(err)
	}
}

func TestStrNotEnoughDataForLength64(t *testing.T) {
	bin, err := EncodeBuf(strings.Repeat("f", 65853), nil)
	if err != nil {
		panic(err)
	}
	_, err = NewDecoderFromBytes(bin[:len(bin)-1], nil).Decode()
	if err != io.ErrUnexpectedEOF {
		t.Fatal(err)
	}
}

func TestStrTooLong(t *testing.T) {
	bin := make([]byte, 9)
	bin[0] = 0xFF
	for _, l := range []uint64{
		1 << 63,
		(1 << 63) - 63,
		(1 << 63) - 63 - ((1 << 8) - 1),
		(1 << 63) - 63 - ((1 << 8) - 1) - ((1 << 16) - 1) + 1,
	} {
		be.Put(bin[1:], l)
		decoder := NewDecoderFromBytes(bin, nil)
		_, err := decoder.Decode()
		if err != ErrLenTooBig {
			t.Fatal(err)
		}
	}
}

func TestStrNotTooLong(t *testing.T) {
	bin := make([]byte, 9)
	bin[0] = 0xFF
	be.Put(bin[1:], (1<<63)-63-((1<<8)-1)-((1<<16)-1))
	decoder := NewDecoderFromReader(bytes.NewReader(bin), nil)
	defer func() { recover() }()
	_, err := decoder.Decode()
	// it won't reach that code because it can not allocate so much
	// memory in .getBytes(), but that means, that no error was returned
	t.Fatal(err)
}

func TestStrMaxStrLen(t *testing.T) {
	f := func(str string) bool {
		if str == "" {
			return true
		}
		encoded, err := EncodeBuf(str, nil)
		if err != nil {
			panic(err)
		}
		decoder := NewDecoderFromBytes(encoded,
			&DecodeOpts{DisableUTF8Check: true, MaxStrLen: int64(len(str) + 1)})
		_, err = decoder.Decode()
		if err != nil {
			return false
		}
		decoder = NewDecoderFromBytes(encoded,
			&DecodeOpts{DisableUTF8Check: true, MaxStrLen: int64(len(str))})
		_, err = decoder.Decode()
		if err != nil {
			return false
		}
		if len(str) == 1 {
			return true
		}
		decoder = NewDecoderFromBytes(encoded,
			&DecodeOpts{DisableUTF8Check: true, MaxStrLen: int64(len(str) - 1)})
		_, err = decoder.Decode()
		return err != nil
	}
	if err := quick.Check(f, nil); err != nil {
		t.Fatal(err)
	}
}

func TestStrSymmetric(t *testing.T) {
	f := func(str string) bool {
		encoded, err := EncodeBuf(str, nil)
		if err != nil {
			panic(err)
		}
		decoder := NewDecoderFromBytes(
			append(encoded, Junk...),
			&DecodeOpts{DisableUTF8Check: true},
		)
		decoded, err := decoder.Decode()
		if err != nil {
			return false
		}
		casted, ok := decoded.(string)
		if !ok {
			return false
		}
		if str != casted {
			return false
		}
		return bytes.Equal(decoder.B, Junk)
	}
	if err := quick.Check(f, nil); err != nil {
		t.Fatal(err)
	}
}
