package native

import (
	"fmt"
	"math"

	"git.marketally.com/tutus-one/tutus-chain/pkg/config"
	"git.marketally.com/tutus-one/tutus-chain/pkg/core/dao"
	"git.marketally.com/tutus-one/tutus-chain/pkg/core/interop"
	"git.marketally.com/tutus-one/tutus-chain/pkg/core/native/nativeids"
	"git.marketally.com/tutus-one/tutus-chain/pkg/core/native/nativenames"
	"git.marketally.com/tutus-one/tutus-chain/pkg/core/transaction"
	"git.marketally.com/tutus-one/tutus-chain/pkg/smartcontract"
	"git.marketally.com/tutus-one/tutus-chain/pkg/smartcontract/callflag"
	"git.marketally.com/tutus-one/tutus-chain/pkg/smartcontract/manifest"
	"git.marketally.com/tutus-one/tutus-chain/pkg/util"
	"git.marketally.com/tutus-one/tutus-chain/pkg/vm/stackitem"
	"git.marketally.com/tutus-one/tutus-chain/pkg/vm/vmstate"
)

// Ledger provides an interface to blocks/transactions storage for smart
// contracts. It's not a part of the proper chain's state, so it's just a
// proxy between regular Blockchain/DAO interface and smart contracts.
type Ledger struct {
	interop.ContractMD
	Policy IPolicy
}

// NewLedger creates a new Ledger native contract.
func NewLedger() *Ledger {
	var l = &Ledger{
		ContractMD: *interop.NewContractMD(nativenames.Ledger, nativeids.LedgerContract),
	}
	defer l.BuildHFSpecificMD(l.ActiveIn())

	desc := NewDescriptor("currentHash", smartcontract.Hash256Type)
	md := NewMethodAndPrice(l.currentHash, 1<<15, callflag.ReadStates)
	l.AddMethod(md, desc)

	desc = NewDescriptor("currentIndex", smartcontract.IntegerType)
	md = NewMethodAndPrice(l.currentIndex, 1<<15, callflag.ReadStates)
	l.AddMethod(md, desc)

	desc = NewDescriptor("getBlock", smartcontract.ArrayType,
		manifest.NewParameter("indexOrHash", smartcontract.ByteArrayType))
	md = NewMethodAndPrice(l.getBlock, 1<<15, callflag.ReadStates)
	l.AddMethod(md, desc)

	desc = NewDescriptor("getTransaction", smartcontract.ArrayType,
		manifest.NewParameter("hash", smartcontract.Hash256Type))
	md = NewMethodAndPrice(l.getTransaction, 1<<15, callflag.ReadStates)
	l.AddMethod(md, desc)

	desc = NewDescriptor("getTransactionHeight", smartcontract.IntegerType,
		manifest.NewParameter("hash", smartcontract.Hash256Type))
	md = NewMethodAndPrice(l.getTransactionHeight, 1<<15, callflag.ReadStates)
	l.AddMethod(md, desc)

	desc = NewDescriptor("getTransactionFromBlock", smartcontract.ArrayType,
		manifest.NewParameter("blockIndexOrHash", smartcontract.ByteArrayType),
		manifest.NewParameter("txIndex", smartcontract.IntegerType))
	md = NewMethodAndPrice(l.getTransactionFromBlock, 1<<16, callflag.ReadStates)
	l.AddMethod(md, desc)

	desc = NewDescriptor("getTransactionSigners", smartcontract.ArrayType,
		manifest.NewParameter("hash", smartcontract.Hash256Type))
	md = NewMethodAndPrice(l.getTransactionSigners, 1<<15, callflag.ReadStates)
	l.AddMethod(md, desc)

	desc = NewDescriptor("getTransactionVMState", smartcontract.IntegerType,
		manifest.NewParameter("hash", smartcontract.Hash256Type))
	md = NewMethodAndPrice(l.getTransactionVMState, 1<<15, callflag.ReadStates)
	l.AddMethod(md, desc)

	return l
}

// Metadata implements the Contract interface.
func (l *Ledger) Metadata() *interop.ContractMD {
	return &l.ContractMD
}

// Initialize implements the Contract interface.
func (l *Ledger) Initialize(ic *interop.Context, hf *config.Hardfork, newMD *interop.HFSpecificContractMD) error {
	return nil
}

// InitializeCache implements the Contract interface.
func (l *Ledger) InitializeCache(_ interop.IsHardforkEnabled, blockHeight uint32, d *dao.Simple) error {
	return nil
}

// OnPersist implements the Contract interface.
func (l *Ledger) OnPersist(ic *interop.Context) error {
	// Actual block/tx processing is done in Blockchain.storeBlock().
	// Even though C# node add them to storage here, they're not
	// accessible to smart contracts (see isTraceableBlock()), thus
	// the end effect is the same.
	return nil
}

// PostPersist implements the Contract interface.
func (l *Ledger) PostPersist(ic *interop.Context) error {
	ic.IsBlockPersisted = true
	return nil // Actual block/tx processing is done in Blockchain.storeBlock().
}

// ActiveIn implements the Contract interface.
func (l *Ledger) ActiveIn() *config.Hardfork {
	return nil
}

// currentHash implements currentHash SC method.
func (l *Ledger) currentHash(ic *interop.Context, _ []stackitem.Item) stackitem.Item {
	return stackitem.Make(ic.CurrentBlockHash().BytesBE())
}

// currentIndex implements currentIndex SC method.
func (l *Ledger) currentIndex(ic *interop.Context, _ []stackitem.Item) stackitem.Item {
	return stackitem.Make(ic.BlockHeight())
}

// getBlock implements getBlock SC method.
func (l *Ledger) getBlock(ic *interop.Context, params []stackitem.Item) stackitem.Item {
	hash := getBlockHashFromItem(ic, params[0])
	block, err := ic.GetBlock(hash)
	if err != nil || !l.isTraceableBlock(ic, block.Index) {
		return stackitem.Null{}
	}
	return block.ToStackItem()
}

// getTransaction returns transaction to the SC.
func (l *Ledger) getTransaction(ic *interop.Context, params []stackitem.Item) stackitem.Item {
	tx, h, err := getTransactionAndHeight(ic.DAO, params[0])
	if err != nil || !l.isTraceableBlock(ic, h) {
		return stackitem.Null{}
	}
	return tx.ToStackItem()
}

// getTransactionHeight returns transaction height to the SC.
func (l *Ledger) getTransactionHeight(ic *interop.Context, params []stackitem.Item) stackitem.Item {
	_, h, err := getTransactionAndHeight(ic.DAO, params[0])
	if err != nil || !l.isTraceableBlock(ic, h) {
		return stackitem.Make(-1)
	}
	return stackitem.Make(h)
}

// getTransactionFromBlock returns a transaction with the given index from the
// block with the height or hash specified.
func (l *Ledger) getTransactionFromBlock(ic *interop.Context, params []stackitem.Item) stackitem.Item {
	hash := getBlockHashFromItem(ic, params[0])
	index := toUint32(params[1])
	block, err := ic.GetBlock(hash)
	if err != nil || !l.isTraceableBlock(ic, block.Index) {
		return stackitem.Null{}
	}
	if index >= uint32(len(block.Transactions)) {
		panic("wrong transaction index")
	}
	return block.Transactions[index].ToStackItem()
}

// getTransactionSigners returns transaction signers to the SC.
func (l *Ledger) getTransactionSigners(ic *interop.Context, params []stackitem.Item) stackitem.Item {
	tx, h, err := getTransactionAndHeight(ic.DAO, params[0])
	if err != nil || !l.isTraceableBlock(ic, h) {
		return stackitem.Null{}
	}
	return transaction.SignersToStackItem(tx.Signers)
}

// getTransactionVMState returns VM state got after transaction invocation.
func (l *Ledger) getTransactionVMState(ic *interop.Context, params []stackitem.Item) stackitem.Item {
	hash, err := getUint256FromItem(params[0])
	if err != nil {
		panic(err)
	}
	h, _, aer, err := ic.DAO.GetTxExecResult(hash)
	if err != nil || !l.isTraceableBlock(ic, h) {
		return stackitem.Make(vmstate.None)
	}
	return stackitem.Make(aer.VMState)
}

// isTraceableBlock defines whether we're able to give information about
// the block with the index specified.
func (l *Ledger) isTraceableBlock(ic *interop.Context, index uint32) bool {
	height := ic.BlockHeight()
	maxTraceableBlocks := ic.Chain.GetConfig().MaxTraceableBlocks
	if ic.IsHardforkEnabled(config.HFEchidna) {
		maxTraceableBlocks = l.Policy.GetMaxTraceableBlocksInternal(ic.DAO)
	}
	return index <= height && index+maxTraceableBlocks > height
}

// getBlockHashFromItem converts the given stackitem.Item to a block hash using the given
// Ledger if needed. Interop functions accept both block numbers and
// block hashes as parameters, thus this function is needed. It's supposed to
// be called within VM context, so it panics if anything goes wrong.
func getBlockHashFromItem(ic *interop.Context, item stackitem.Item) util.Uint256 {
	bigindex, err := item.TryInteger()
	if err == nil && bigindex.IsUint64() {
		index := bigindex.Uint64()
		if index > math.MaxUint32 {
			panic("bad block index")
		}
		if uint32(index) > ic.BlockHeight() {
			panic(fmt.Errorf("no block with index %d", index))
		}
		return ic.Chain.GetHeaderHash(uint32(index))
	}
	hash, err := getUint256FromItem(item)
	if err != nil {
		panic(err)
	}
	return hash
}

func getUint256FromItem(item stackitem.Item) (util.Uint256, error) {
	hashbytes, err := item.TryBytes()
	if err != nil {
		return util.Uint256{}, fmt.Errorf("failed to get hash bytes: %w", err)
	}
	hash, err := util.Uint256DecodeBytesBE(hashbytes)
	if err != nil {
		return util.Uint256{}, fmt.Errorf("failed to decode hash: %w", err)
	}
	return hash, nil
}

// getTransactionAndHeight returns a transaction and its height if it's present
// on the chain. It panics if anything goes wrong.
func getTransactionAndHeight(d *dao.Simple, item stackitem.Item) (*transaction.Transaction, uint32, error) {
	hash, err := getUint256FromItem(item)
	if err != nil {
		panic(err)
	}
	return d.GetTransaction(hash)
}
