import fs from 'fs/promises';
import path from 'path';
import { numberToHex, } from 'viem';
const DEFAULT_OUTPUT_DIR = path.join('broadcast', 'multi');
export const writeMultichainBroadcast = async (multichainBroadcast) => {
    const { transactions, address, name, timestamp, type, contractArguments, foundryProjectRoot, } = multichainBroadcast;
    if (!Object.keys(transactions).length) {
        return;
    }
    const outputDir = path.join(foundryProjectRoot, DEFAULT_OUTPUT_DIR);
    const runArtifact = {
        deployments: [],
        timestamp,
    };
    Object.keys(transactions).forEach(chainIdStr => {
        const chainId = Number(chainIdStr);
        if (!transactions[chainId]) {
            return;
        }
        const { hash, transaction, receipt } = transactions[chainId];
        const transactionData = {
            hash,
            transactionType: type,
            contractName: name,
            contractAddress: address,
            function: null,
            arguments: contractArguments,
            transaction: {
                from: receipt.from,
                to: receipt.to,
                gas: transaction.gas,
                value: transaction.value,
                input: transaction.input,
                nonce: numberToHex(transaction.nonce),
                chainId: numberToHex(chainId),
                additionalContracts: [],
                isFixedGasLimit: false,
            },
        };
        const receiptData = {
            status: receipt.status === 'success' ? '0x1' : '0x0',
            cumulativeGasUsed: receipt.cumulativeGasUsed,
            logs: receipt.logs,
            logsBloom: receipt.logsBloom,
            type: transaction.typeHex,
            transactionHash: receipt.transactionHash,
            transactionIndex: numberToHex(receipt.transactionIndex),
            blockHash: receipt.blockHash,
            blockNumber: receipt.blockNumber,
            gasUsed: receipt.gasUsed,
            effectiveGasPrice: receipt.effectiveGasPrice,
            blobGasPrice: receipt.blobGasPrice,
            from: receipt.from,
            to: receipt.to,
            contractAddress: receipt.contractAddress,
        };
        const deployment = {
            transactions: [transactionData],
            receipts: [receiptData],
            timestamp,
            chain: chainId,
        };
        runArtifact.deployments.push(deployment);
    });
    const latestDirname = path.join(outputDir, `${name}-latest`);
    const timestampDirname = path.join(outputDir, `${name}-${timestamp}`);
    await fs.mkdir(latestDirname, { recursive: true });
    await fs.mkdir(timestampDirname, { recursive: true });
    const fileContents = JSON.stringify(runArtifact, (_, val) => (typeof val === 'bigint' ? numberToHex(val) : val), 2);
    await fs.writeFile(path.join(latestDirname, 'run.json'), fileContents);
    await fs.writeFile(path.join(timestampDirname, 'run.json'), fileContents);
};
