// Copyright (c) 2017-2026 Lethean (https://lt.hn)
//
// Licensed under the European Union Public Licence (EUPL) version 1.2.
// SPDX-License-Identifier: EUPL-1.2

package consensus

import (
	"fmt"

	coreerr "dappco.re/go/core/log"

	"dappco.re/go/core/blockchain/config"
	"dappco.re/go/core/blockchain/types"
	"dappco.re/go/core/blockchain/wire"
)

type txForkState struct {
	currentFork uint8
	hf1Active   bool
	hf4Active   bool
	hf5Active   bool
}

func newTxForkState(forks []config.HardFork, height uint64) txForkState {
	return txForkState{
		currentFork: config.VersionAtHeight(forks, height),
		hf1Active:   config.IsHardForkActive(forks, config.HF1, height),
		hf4Active:   config.IsHardForkActive(forks, config.HF4Zarcanum, height),
		hf5Active:   config.IsHardForkActive(forks, config.HF5, height),
	}
}

// ValidateTransaction performs semantic validation on a regular (non-coinbase)
// transaction. Checks are ordered to match the C++ validate_tx_semantic().
func ValidateTransaction(tx *types.Transaction, txBlob []byte, forks []config.HardFork, height uint64) error {
	state := newTxForkState(forks, height)

	// 0. Transaction version.
	if err := checkTxVersion(tx, state, height); err != nil {
		return err
	}

	// 1. Blob size.
	if uint64(len(txBlob)) >= config.MaxTransactionBlobSize {
		return coreerr.E("ValidateTransaction", fmt.Sprintf("%d bytes", len(txBlob)), ErrTxTooLarge)
	}

	// 2. Input count.
	if len(tx.Vin) == 0 {
		return ErrNoInputs
	}
	if uint64(len(tx.Vin)) > config.TxMaxAllowedInputs {
		return coreerr.E("ValidateTransaction", fmt.Sprintf("%d", len(tx.Vin)), ErrTooManyInputs)
	}

	// 3. Input types — TxInputGenesis not allowed in regular transactions.
	if err := checkInputTypes(tx, state); err != nil {
		return err
	}

	// 4. Output validation.
	if err := checkOutputs(tx, state); err != nil {
		return err
	}

	// 4a. HF5 asset operation validation inside extra.
	if err := checkAssetOperations(tx.Extra, state.hf5Active); err != nil {
		return err
	}

	// 5. Money overflow.
	if _, err := sumInputs(tx); err != nil {
		return err
	}
	if _, err := sumOutputs(tx); err != nil {
		return err
	}

	// 6. Key image uniqueness.
	if err := checkKeyImages(tx); err != nil {
		return err
	}

	// 7. Balance check (pre-HF4 only — post-HF4 uses commitment proofs).
	if !state.hf4Active {
		if _, err := TxFee(tx); err != nil {
			return err
		}
	}

	return nil
}

// checkTxVersion validates that the transaction version is appropriate for the
// current hardfork era.
//
// Pre-HF4: regular transactions must use version 1.
// HF4 era: regular transactions must use version 2.
// HF5+: transaction version must be exactly version 3 and the embedded
// hardfork_id must match the active hardfork version.
func checkTxVersion(tx *types.Transaction, state txForkState, height uint64) error {
	var expectedVersion uint64
	switch {
	case state.hf5Active:
		expectedVersion = types.VersionPostHF5
	case state.hf4Active:
		expectedVersion = types.VersionPostHF4
	default:
		expectedVersion = types.VersionPreHF4
	}

	if tx.Version != expectedVersion {
		return coreerr.E("checkTxVersion",
			fmt.Sprintf("version %d invalid at height %d (expected %d)", tx.Version, height, expectedVersion),
			ErrTxVersionInvalid)
	}

	if tx.Version >= types.VersionPostHF5 && tx.HardforkID != state.currentFork {
		return coreerr.E("checkTxVersion",
			fmt.Sprintf("hardfork id %d does not match active fork %d at height %d", tx.HardforkID, state.currentFork, height),
			ErrTxVersionInvalid)
	}

	return nil
}

func checkInputTypes(tx *types.Transaction, state txForkState) error {
	for _, vin := range tx.Vin {
		switch vin.(type) {
		case types.TxInputToKey:
			// Always valid.
		case types.TxInputGenesis:
			return coreerr.E("checkInputTypes", "txin_gen in regular transaction", ErrInvalidInputType)
		case types.TxInputHTLC, types.TxInputMultisig:
			// HTLC and multisig inputs require at least HF1.
			if !state.hf1Active {
				return coreerr.E("checkInputTypes", fmt.Sprintf("tag %d pre-HF1", vin.InputType()), ErrInvalidInputType)
			}
		case types.TxInputZC:
			if !state.hf4Active {
				return coreerr.E("checkInputTypes", fmt.Sprintf("tag %d pre-HF4", vin.InputType()), ErrInvalidInputType)
			}
		default:
			return coreerr.E("checkInputTypes", fmt.Sprintf("unsupported input type %T", vin), ErrInvalidInputType)
		}
	}
	return nil
}

func checkOutputs(tx *types.Transaction, state txForkState) error {
	if len(tx.Vout) == 0 {
		return ErrNoOutputs
	}

	if state.hf4Active && uint64(len(tx.Vout)) < config.TxMinAllowedOutputs {
		return coreerr.E("checkOutputs", fmt.Sprintf("%d (min %d)", len(tx.Vout), config.TxMinAllowedOutputs), ErrTooFewOutputs)
	}

	if uint64(len(tx.Vout)) > config.TxMaxAllowedOutputs {
		return coreerr.E("checkOutputs", fmt.Sprintf("%d", len(tx.Vout)), ErrTooManyOutputs)
	}

	for i, vout := range tx.Vout {
		switch o := vout.(type) {
		case types.TxOutputBare:
			if o.Amount == 0 {
				return coreerr.E("checkOutputs", fmt.Sprintf("output %d has zero amount", i), ErrInvalidOutput)
			}
			// Only known transparent output targets are accepted.
			switch o.Target.(type) {
			case types.TxOutToKey:
			case types.TxOutHTLC, types.TxOutMultisig:
				if !state.hf1Active {
					return coreerr.E("checkOutputs", fmt.Sprintf("output %d: HTLC/multisig target pre-HF1", i), ErrInvalidOutput)
				}
			case nil:
				return coreerr.E("checkOutputs", fmt.Sprintf("output %d: missing target", i), ErrInvalidOutput)
			default:
				return coreerr.E("checkOutputs", fmt.Sprintf("output %d: unsupported target %T", i, o.Target), ErrInvalidOutput)
			}
		case types.TxOutputZarcanum:
			if !state.hf4Active {
				return coreerr.E("checkOutputs", fmt.Sprintf("output %d: Zarcanum output pre-HF4", i), ErrInvalidOutput)
			}
		default:
			return coreerr.E("checkOutputs", fmt.Sprintf("output %d: unsupported output type %T", i, vout), ErrInvalidOutput)
		}
	}

	return nil
}

func checkKeyImages(tx *types.Transaction) error {
	seen := make(map[types.KeyImage]struct{})
	for _, vin := range tx.Vin {
		var ki types.KeyImage
		switch v := vin.(type) {
		case types.TxInputToKey:
			ki = v.KeyImage
		case types.TxInputHTLC:
			ki = v.KeyImage
		default:
			continue
		}
		if _, exists := seen[ki]; exists {
			return coreerr.E("checkKeyImages", ki.String(), ErrDuplicateKeyImage)
		}
		seen[ki] = struct{}{}
	}
	return nil
}

func checkAssetOperations(extra []byte, hf5Active bool) error {
	if len(extra) == 0 {
		return nil
	}

	elements, err := wire.DecodeVariantVector(extra)
	if err != nil {
		return coreerr.E("checkAssetOperations", "parse extra", ErrInvalidExtra)
	}

	for i, elem := range elements {
		if elem.Tag != types.AssetDescriptorOperationTag {
			continue
		}
		if !hf5Active {
			return coreerr.E("checkAssetOperations", fmt.Sprintf("extra[%d]: asset descriptor operation pre-HF5", i), ErrInvalidExtra)
		}

		op, err := wire.DecodeAssetDescriptorOperation(elem.Data)
		if err != nil {
			return coreerr.E("checkAssetOperations", fmt.Sprintf("extra[%d]: decode asset descriptor operation", i), ErrInvalidExtra)
		}
		if err := op.Validate(); err != nil {
			return coreerr.E("checkAssetOperations", fmt.Sprintf("extra[%d]", i), err)
		}
	}

	return nil
}
