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

async function main() {
  const cfg = parseEnvConfig(resolveConfigPath(process.argv[2]));
  const proposal = new PublicKey(process.argv[3]);
  const proposalTx = new PublicKey(process.argv[4]);
  const nftMint = new PublicKey(process.argv[5]);
  const target = new PublicKey(process.argv[6]);
  if (!process.argv[6]) throw new Error("Usage: node 03_execute_mint_nft.js <config.env> <proposal> <proposalTx> <nftMint> <targetWallet>");
  const conn = new Connection(clusterUrl(cfg.CLUSTER), "confirmed");
  const main = loadKeypair(path.resolve(__dirname, cfg.MAIN_KEYPAIR));
  const governance = new PublicKey(cfg.GOVERNANCE); const govPid = new PublicKey(cfg.SPL_GOVERNANCE_PROGRAM_ID);
  const targetAta = getAssociatedTokenAddressSync(nftMint, target, false, TOKEN_2022_PROGRAM_ID);
  const ataExists = (await conn.getAccountInfo(targetAta, "confirmed")) !== null;
  if (!ataExists) throw new Error(`Target ATA not found. Create it first: ${targetAta.toBase58()}`);
  const mintIx = [
    createMintToInstruction(nftMint, targetAta, governance, 1n, [], TOKEN_2022_PROGRAM_ID),
  ].map(toInstructionData);
  const ix = [];
  await withExecuteTransaction(ix, govPid, PROGRAM_VERSION_V3, governance, proposal, proposalTx, mintIx);
  const sig = await sendAndConfirmTransaction(conn, new Transaction().add(...ix), [main], { commitment: "confirmed" });
  console.log("execute mint done:", sig);
}
main().catch((e)=>{console.error(e?.message||e);process.exit(1);});
