#!/usr/bin/env node
"use strict";
const path = require("path");
const BN = require("bn.js");
const { Connection, Transaction, sendAndConfirmTransaction } = require("@solana/web3.js");
const { getAssociatedTokenAddressSync, createAssociatedTokenAccountIdempotentInstruction, createMintToInstruction, TOKEN_PROGRAM_ID } = require("@solana/spl-token");
const { withDepositGoverningTokens, PROGRAM_VERSION_V3, getTokenOwnerRecordAddress } = require("@solana/spl-governance");
const { parseEnvConfig, resolveConfigPath, loadKeypair, clusterUrl, PublicKey } = require("./js_common");

async function main() {
  const cfg = parseEnvConfig(resolveConfigPath(process.argv[2]));
  const conn = new Connection(clusterUrl(cfg.CLUSTER), "confirmed");
  const main = loadKeypair(path.resolve(__dirname, cfg.MAIN_KEYPAIR));
  const voter2 = loadKeypair(path.resolve(__dirname, cfg.VOTER2_KEYPAIR));
  const realm = new PublicKey(cfg.REALM);
  const mint = new PublicKey(cfg.GOVERNING_MINT);
  const govPid = new PublicKey(cfg.SPL_GOVERNANCE_PROGRAM_ID);

  const ata = getAssociatedTokenAddressSync(mint, voter2.publicKey, false, TOKEN_PROGRAM_ID);
  const ix1 = [
    createAssociatedTokenAccountIdempotentInstruction(main.publicKey, ata, voter2.publicKey, mint, TOKEN_PROGRAM_ID),
    createMintToInstruction(mint, ata, main.publicKey, 1n, [], TOKEN_PROGRAM_ID),
  ];
  const sigMint = await sendAndConfirmTransaction(conn, new Transaction().add(...ix1), [main], { commitment: "confirmed" });

  const tor = await getTokenOwnerRecordAddress(govPid, realm, mint, voter2.publicKey);
  const ai = await conn.getAccountInfo(tor, "confirmed");
  let sigDeposit = null;
  if (!ai) {
    const ix2 = [];
    await withDepositGoverningTokens(ix2, govPid, PROGRAM_VERSION_V3, realm, ata, mint, voter2.publicKey, main.publicKey, voter2.publicKey, new BN(1), true);
    sigDeposit = await sendAndConfirmTransaction(conn, new Transaction().add(...ix2), [main, voter2], { commitment: "confirmed" });
  }
  console.log("prepare done");
  console.log("mint tx:", sigMint);
  console.log("deposit tx:", sigDeposit || "already exists");
}
main().catch((e) => { console.error(e?.message || e); process.exit(1); });
