#!/usr/bin/env node
"use strict";
const fs = require("fs");
const path = require("path");
const { Connection, SystemProgram, Transaction, sendAndConfirmTransaction } = require("@solana/web3.js");
const { TOKEN_PROGRAM_ID, getMintLen, createInitializeMintInstruction } = require("@solana/spl-token");
const { parseEnvConfig, assertRequired, resolveConfigPath, loadKeypair, findSingleJsonFile, saveKeypair, parseCluster, nowStamp, ui, getOperatorKeypairFromConfig } = require("./_common");

async function main() {
  const cfg = parseEnvConfig(resolveConfigPath(process.argv[2]));
  assertRequired(cfg, "GT_CLUSTER"); assertRequired(cfg, "GT_RUNS_DIR");
  const operator = getOperatorKeypairFromConfig(cfg);
  const connection = new Connection(parseCluster(cfg.GT_CLUSTER), "confirmed");
  const gtDir = path.resolve(cfg.GT_GOVERNMENT_TOKEN_KEYPAIR_DIR || path.join(__dirname, "..", "keypairs", "government_token"));
  fs.mkdirSync(gtDir, { recursive: true });
  const mintKeypairPath = findSingleJsonFile(gtDir);
  const mint = loadKeypair(mintKeypairPath);
  const mintLen = getMintLen([]);
  const rent = await connection.getMinimumBalanceForRentExemption(mintLen, "confirmed");
  ui.title("=== Создание governance token (SPL classic) / Create governance token (SPL classic) ===");
  const tx = new Transaction().add(
    SystemProgram.createAccount({ fromPubkey: operator.publicKey, newAccountPubkey: mint.publicKey, space: mintLen, lamports: rent, programId: TOKEN_PROGRAM_ID }),
    createInitializeMintInstruction(mint.publicKey, 0, operator.publicKey, operator.publicKey, TOKEN_PROGRAM_ID)
  );
  const sig = await sendAndConfirmTransaction(connection, tx, [operator, mint], { commitment: "confirmed" });
  const runsDir = path.resolve(cfg.GT_RUNS_DIR); fs.mkdirSync(runsDir, { recursive: true });
  const outMintPath = mintKeypairPath;
  saveKeypair(outMintPath, mint);
  fs.writeFileSync(path.join(runsDir, `${nowStamp()}_create_token.json`), JSON.stringify({ mint: mint.publicKey.toBase58(), txCreateMint: sig }, null, 2));
  ui.ok(`OK: Mint ${mint.publicKey.toBase58()}`);
  ui.info(`RU: Использован keypair: ${mintKeypairPath}`);
  ui.info(`EN: Used keypair: ${mintKeypairPath}`);
  ui.info(`RU: Вставьте этот mint в файл: ${path.resolve(__dirname, "..", "governance_token.config.env")}`);
  ui.info(`RU: Строка: GT_MINT_ADDRESS="${mint.publicKey.toBase58()}"`);
  ui.info(`EN: Put this mint into file: ${path.resolve(__dirname, "..", "governance_token.config.env")}`);
  ui.info(`EN: Line: GT_MINT_ADDRESS="${mint.publicKey.toBase58()}"`);
  ui.info(`Mint keypair: ${outMintPath}`);
  ui.info(`Tx: ${sig}`);
}
main().catch((e) => { ui.err(`Ошибка / Error: ${e?.message || e}`); process.exit(1); });
