package miner

import (
	"math/big"
	"strings"
	"testing"
)

func TestUint32ToHexLittleEndian(t *testing.T) {
	got := uint32ToHex(0x01020304)
	want := "04030201"
	if got != want {
		t.Fatalf("uint32ToHex(0x01020304) = %q, want %q", got, want)
	}
}

func TestUint32ToHexZero(t *testing.T) {
	if got := uint32ToHex(0); got != "00000000" {
		t.Fatalf("zero nonce hex = %q", got)
	}
}

func TestHexEncode(t *testing.T) {
	if got := hexEncode([]byte{0xde, 0xad, 0xbe, 0xef}); got != "deadbeef" {
		t.Fatalf("hexEncode = %q", got)
	}
}

func TestDifficultyToTargetHexZero(t *testing.T) {
	if difficultyToTargetHex(0) != "" {
		t.Fatal("difficulty 0 should yield empty target")
	}
	if difficultyToTargetHex(-1) != "" {
		t.Fatal("negative difficulty should yield empty target")
	}
}

func TestDifficultyToTargetHexOne(t *testing.T) {
	out := difficultyToTargetHex(1)
	want := strings.Repeat("f", 64)
	if out != want {
		t.Fatalf("difficulty 1 target = %q, want %q", out, want)
	}
}

func TestDifficultyToTargetHexTwo(t *testing.T) {
	out := difficultyToTargetHex(2)
	maxTarget := new(big.Int)
	maxTarget.SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16)
	half := new(big.Int).Div(maxTarget, big.NewInt(2))
	// difficultyToTargetHex reverses byte order before hex encoding
	bytes := half.Bytes()
	padded := make([]byte, 32)
	copy(padded[32-len(bytes):], bytes)
	for i, j := 0, len(padded)-1; i < j; i, j = i+1, j-1 {
		padded[i], padded[j] = padded[j], padded[i]
	}
	want := strings.ToLower(strings.Repeat("", 0)) // placeholder
	_ = want
	const hexdigits = "0123456789abcdef"
	wantBytes := make([]byte, 64)
	for i, v := range padded {
		wantBytes[i*2] = hexdigits[v>>4]
		wantBytes[i*2+1] = hexdigits[v&0x0f]
	}
	want = string(wantBytes)
	if out != want {
		t.Fatalf("difficulty 2 target = %q, want %q", out, want)
	}
}

func TestDifficultyToTargetHexLength(t *testing.T) {
	for _, d := range []int64{1, 100, 1000, 1_000_000} {
		out := difficultyToTargetHex(d)
		if len(out) != 64 {
			t.Fatalf("difficulty %d: expected 64 hex chars, got %d (%q)", d, len(out), out)
		}
	}
}

func TestDifficultyToTargetMeetsHash(t *testing.T) {
	target := difficultyToTargetHex(1000)
	zeroHash := strings.Repeat("0", 64)
	if !hashMeetsTarget(zeroHash, target) {
		t.Fatal("zero hash should meet difficulty-derived target")
	}
	highHash := strings.Repeat("f", 64)
	if hashMeetsTarget(highHash, target) {
		t.Fatal("max hash should not meet difficulty-derived target")
	}
}
