import { getEthBlobEvaluationInputs, getPrefixedEthBlobCommitments } from '@aztec/blob-lib';
import { writeFile } from 'fs/promises';
const AZTEC_GENERATE_TEST_DATA = !!process.env.AZTEC_GENERATE_TEST_DATA;
/**
 * Creates a json object that can be used to test the solidity contract.
 * The json object must be put into
 */ export async function writeJson(fileName, checkpointHeader, block, l1ToL2Content, blobs, batchedBlob, recipientAddress, deployerAddress) {
    if (!AZTEC_GENERATE_TEST_DATA) {
        return;
    }
    // Path relative to the package.json in the end-to-end folder
    const path = `../../l1-contracts/test/fixtures/${fileName}.json`;
    const asHex = (value, size = 64)=>{
        const buffer = Buffer.isBuffer(value) ? value : value.toBuffer();
        return `0x${buffer.toString('hex').padStart(size, '0')}`;
    };
    const jsonObject = {
        populate: {
            l1ToL2Content: l1ToL2Content.map((value)=>asHex(value)),
            recipient: asHex(recipientAddress.toField()),
            sender: deployerAddress
        },
        messages: {
            l2ToL1Messages: block.body.txEffects.flatMap((txEffect)=>txEffect.l2ToL1Msgs).map((value)=>asHex(value))
        },
        checkpoint: {
            // The json formatting in forge is a bit brittle, so we convert Fr to a number in the few values below.
            // This should not be a problem for testing as long as the values are not larger than u32.
            archive: asHex(block.archive.root),
            blobCommitments: getPrefixedEthBlobCommitments(blobs),
            batchedBlobInputs: getEthBlobEvaluationInputs(batchedBlob),
            checkpointNumber: block.number,
            body: `0x${block.body.toBuffer().toString('hex')}`,
            header: {
                lastArchiveRoot: asHex(checkpointHeader.lastArchiveRoot),
                blockHeadersHash: asHex(checkpointHeader.blockHeadersHash),
                blobsHash: asHex(checkpointHeader.blobsHash),
                inHash: asHex(checkpointHeader.inHash),
                outHash: asHex(checkpointHeader.epochOutHash),
                slotNumber: Number(checkpointHeader.slotNumber),
                timestamp: Number(checkpointHeader.timestamp),
                coinbase: asHex(checkpointHeader.coinbase, 40),
                feeRecipient: asHex(checkpointHeader.feeRecipient),
                gasFees: {
                    feePerDaGas: Number(checkpointHeader.gasFees.feePerDaGas),
                    feePerL2Gas: Number(checkpointHeader.gasFees.feePerL2Gas)
                },
                totalManaUsed: checkpointHeader.totalManaUsed.toNumber()
            },
            headerHash: asHex(checkpointHeader.hash()),
            numTxs: block.body.txEffects.length
        }
    };
    const output = JSON.stringify(jsonObject, null, 2);
    await writeFile(path, output, 'utf8');
}
