/* This file is part of DarkFi (https://dark.fi)
 *
 * Copyright (C) 2020-2026 Dyne.org foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use std::slice;

use darkfi::{
    blockchain::{BlockInfo, BlockchainOverlay, Header},
    tx::{ContractCallLeaf, Transaction, TransactionBuilder},
    validator::verification::apply_producer_transaction,
    Result,
};
use darkfi_money_contract::{
    client::{pow_reward_v1::PoWRewardCallBuilder, OwnCoin},
    model::MoneyPoWRewardParamsV1,
    MoneyFunction, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
};
use darkfi_sdk::{
    crypto::{contract_id::MONEY_CONTRACT_ID, MerkleTree},
    ContractCall,
};
use darkfi_serial::Encodable;
use tracing::info;

use super::{Holder, TestHarness};

impl TestHarness {
    /// Create a `Money::PoWReward` transaction for a given [`Holder`].
    ///
    /// Optionally takes a specific reward recipient and a nonstandard
    /// reward value.
    /// Returns the created [`Transaction`] and [`MoneyPoWRewardParamsV1`].
    async fn pow_reward(
        &mut self,
        holder: &Holder,
        recipient: Option<&Holder>,
        reward: Option<u64>,
        fees: Option<u64>,
    ) -> Result<(Transaction, MoneyPoWRewardParamsV1)> {
        let wallet = self.wallet(holder);

        let (mint_pk, mint_zkbin) = self.proving_keys.get(MONEY_CONTRACT_ZKAS_MINT_NS_V1).unwrap();

        // Reference the last block in the holder's blockchain
        let last_block = wallet.validator.read().await.blockchain.last_block()?;

        // If there's a set reward recipient, use it, otherwise reward the holder
        let recipient = recipient.map(|holder| self.wallet(holder).keypair.public);

        // If there's fees paid, use them, otherwise set to zero
        let fees = fees.unwrap_or_default();

        // Build the transaction
        let builder = PoWRewardCallBuilder {
            signature_keypair: wallet.keypair,
            block_height: last_block.header.height + 1,
            fees,
            recipient,
            spend_hook: None,
            user_data: None,
            mint_zkbin: mint_zkbin.clone(),
            mint_pk: mint_pk.clone(),
        };

        let debris = match reward {
            Some(value) => builder.build_with_custom_reward(value)?,
            None => builder.build()?,
        };

        // Encode the transaction
        let mut data = vec![MoneyFunction::PoWRewardV1 as u8];
        debris.params.encode(&mut data)?;
        let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
        let mut tx_builder =
            TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
        let mut tx = tx_builder.build()?;
        let sigs = tx.create_sigs(&[wallet.keypair.secret])?;
        tx.signatures = vec![sigs];

        Ok((tx, debris.params))
    }

    /// Generate and add an empty block to the given [`Holder`]'s blockchains.
    /// The `miner` holder will produce the block and receive the reward.
    ///
    /// Returns any found [`OwnCoin`]s.
    pub async fn generate_block(
        &mut self,
        miner: &Holder,
        holders: &[Holder],
    ) -> Result<Vec<OwnCoin>> {
        // Build the POW reward transaction
        info!("Building PoWReward transaction for {miner:?}");
        let (tx, params) = self.pow_reward(miner, None, None, None).await?;

        // Fetch the last block in the blockchain
        let wallet = self.wallet(miner);
        let validator = wallet.validator.read().await;
        let previous = validator.blockchain.last_block()?;

        // We increment timestamp so we don't have to use sleep
        let timestamp = previous.header.timestamp.checked_add(1.into())?;

        // Generate block header
        let header = Header::new(
            previous.hash(),
            previous.header.height + 1,
            previous.header.nonce,
            timestamp,
        );

        // Generate the block
        let mut block = BlockInfo::new_empty(header);

        // Add producer transaction to the block
        block.append_txs(vec![tx]);

        // Compute block contracts states monotree root
        let overlay = BlockchainOverlay::new(&validator.blockchain)?;
        let _ = apply_producer_transaction(
            &overlay,
            block.header.height,
            validator.consensus.module.target,
            block.txs.last().unwrap(),
            &mut MerkleTree::new(1),
        )
        .await?;
        drop(validator);

        let diff = overlay.lock().unwrap().overlay.lock().unwrap().diff(&[])?;
        block.header.state_root = overlay.lock().unwrap().contracts.update_state_monotree(&diff)?;

        // Attach signature
        block.sign(&wallet.keypair.secret);

        // For all holders, append the block and process the reward output
        let mut found_owncoins = vec![];
        for holder in holders {
            let wallet = self.wallet_mut(holder);
            wallet.validator.write().await.add_test_blocks(&[block.clone()]).await?;
            found_owncoins.extend(wallet.process_outputs(slice::from_ref(&params.output), holder));
        }

        Ok(found_owncoins)
    }
}
