// Copyright 2024 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library 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, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package era

import (
	"errors"
	"fmt"
	"math/big"
	"slices"

	"github.com/ethereum/go-ethereum/common"
	ssz "github.com/ferranbt/fastssz"
)

// ComputeAccumulator calculates the SSZ hash tree root of the Era1
// accumulator of header records.
func ComputeAccumulator(hashes []common.Hash, tds []*big.Int) (common.Hash, error) {
	if len(hashes) != len(tds) {
		return common.Hash{}, errors.New("must have equal number hashes as td values")
	}
	if len(hashes) > MaxSize {
		return common.Hash{}, fmt.Errorf("too many records: have %d, max %d", len(hashes), MaxSize)
	}
	hh := ssz.NewHasher()
	for i := range hashes {
		rec := headerRecord{hashes[i], tds[i]}
		root, err := rec.HashTreeRoot()
		if err != nil {
			return common.Hash{}, err
		}
		hh.Append(root[:])
	}
	hh.MerkleizeWithMixin(0, uint64(len(hashes)), uint64(MaxSize))
	return hh.HashRoot()
}

// headerRecord is an individual record for a historical header.
//
// See https://github.com/ethereum/portal-network-specs/blob/master/history/history-network.md#the-historical-hashes-accumulator
// for more information.
type headerRecord struct {
	Hash            common.Hash
	TotalDifficulty *big.Int
}

// GetTree completes the ssz.HashRoot interface, but is unused.
func (h *headerRecord) GetTree() (*ssz.Node, error) {
	return nil, nil
}

// HashTreeRoot ssz hashes the headerRecord object.
func (h *headerRecord) HashTreeRoot() ([32]byte, error) {
	return ssz.HashWithDefaultHasher(h)
}

// HashTreeRootWith ssz hashes the headerRecord object with a hasher.
func (h *headerRecord) HashTreeRootWith(hh ssz.HashWalker) (err error) {
	hh.PutBytes(h.Hash[:])
	td := BigToBytes32(h.TotalDifficulty)
	hh.PutBytes(td[:])
	hh.Merkleize(0)
	return
}

// bigToBytes32 converts a big.Int into a little-endian 32-byte array.
func BigToBytes32(n *big.Int) (b [32]byte) {
	n.FillBytes(b[:])
	slices.Reverse(b[:])
	return
}
