package miner

import (
	"encoding/hex"
	"math/big"
)

func hashMeetsTarget(hashHex, targetHex string) bool {
	hashBytes, err := hex.DecodeString(hashHex)
	if err != nil || len(hashBytes) == 0 {
		return false
	}
	targetBytes, err := hex.DecodeString(padHex(targetHex, len(hashBytes)*2))
	if err != nil || len(targetBytes) == 0 {
		return false
	}

	if len(targetBytes) < len(hashBytes) {
		padded := make([]byte, len(hashBytes))
		copy(padded, targetBytes)
		targetBytes = padded
	}
	if len(hashBytes) < len(targetBytes) {
		padded := make([]byte, len(targetBytes))
		copy(padded, hashBytes)
		hashBytes = padded
	}

	hashInt := new(big.Int).SetBytes(reverseBytes(hashBytes))
	targetInt := new(big.Int).SetBytes(reverseBytes(targetBytes))
	return hashInt.Cmp(targetInt) <= 0
}

func padHex(s string, length int) string {
	if len(s) >= length {
		return s
	}
	pad := length - len(s)
	out := make([]byte, length)
	for i := 0; i < pad; i++ {
		out[i] = '0'
	}
	copy(out[pad:], []byte(s))
	return string(out)
}

func reverseBytes(b []byte) []byte {
	out := make([]byte, len(b))
	for i := range b {
		out[i] = b[len(b)-1-i]
	}
	return out
}
