import { createAztecNodeClient } from '@aztec/aztec.js/node';
import { jsonStringify } from '@aztec/foundation/json-rpc';
import { createLogger } from '@aztec/foundation/log';
import { parseWithOptionals, schemaHasMethod } from '@aztec/foundation/schemas';
import { NodeListener, TransportServer } from '@aztec/foundation/transport';
import { Tx } from '@aztec/stdlib/tx';
import { workerData } from 'worker_threads';
import { TestWallet } from './test_wallet.js';
import { WorkerWalletSchema } from './worker_wallet_schema.js';
const logger = createLogger('e2e:test-wallet:worker');
try {
    const { nodeUrl, pxeConfig } = workerData;
    logger.info('Initializing worker wallet', {
        nodeUrl
    });
    const node = createAztecNodeClient(nodeUrl);
    const wallet = await TestWallet.create(node, pxeConfig);
    logger.info('Worker wallet initialized');
    const customMethods = {
        proveTx: async (exec, opts)=>{
            const provenTx = await wallet.proveTx(exec, opts);
            return new Tx(provenTx.getTxHash(), provenTx.data, provenTx.chonkProof, provenTx.contractClassLogFields, provenTx.publicFunctionCalldata);
        },
        registerAccount: async (secret, salt)=>{
            const manager = await wallet.createSchnorrAccount(secret, salt);
            return manager.address;
        }
    };
    const schema = WorkerWalletSchema;
    const listener = new NodeListener();
    const server = new TransportServer(listener, async (msg)=>{
        if (!schemaHasMethod(schema, msg.fn)) {
            throw new Error(`Unknown method: ${msg.fn}`);
        }
        const jsonParams = JSON.parse(msg.args);
        const args = await parseWithOptionals(jsonParams, schema[msg.fn].parameters());
        // we have to erase the fn type in order to be able to spread ...args
        const handler = msg.fn in customMethods ? customMethods[msg.fn] : undefined;
        const result = handler ? await handler(...args) : await wallet[msg.fn](...args);
        return jsonStringify(result);
    });
    server.start();
} catch (err) {
    logger.error('Worker wallet initialization failed', {
        error: err instanceof Error ? err.stack : String(err)
    });
    process.exit(1);
}
