#!/usr/bin/env node
"use strict";
const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");
const { parseEnvConfig, resolveConfigPath, nowStamp, ui } = require("./_common");
const DEFAULT_PREFIX = "SHi";

async function main() {
  const cfg = parseEnvConfig(resolveConfigPath(process.argv[2]));
  const runsDir = path.resolve(cfg.GT_RUNS_DIR || path.join(__dirname, "..", "runs"));
  fs.mkdirSync(runsDir, { recursive: true });
  const prefix = process.argv[3] || cfg.GT_VANITY_PREFIX || DEFAULT_PREFIX;
  if (!/^[1-9A-HJ-NP-Za-km-z]+$/.test(prefix)) throw new Error("Префикс Base58 без 0/O/I/l");
  ui.title("=== Vanity подбор mint keypair / Vanity mint keypair grind ===");
  ui.info(`Prefix: ${prefix}`);
  const args = ["grind", "--starts-with", `${prefix}:1`];
  const p = spawn("solana-keygen", args, { cwd: runsDir, stdio: ["ignore", "pipe", "pipe"] });
  const lines = [];
  const on = (d) => {
    for (const l of String(d).split("\n")) {
      const line = l.trim(); if (!line) continue;
      lines.push(line); console.log(line);
    }
  };
  p.stdout.on("data", on); p.stderr.on("data", on);
  const code = await new Promise((resolve) => p.on("close", resolve));
  if (code !== 0) throw new Error(`solana-keygen grind exit code ${code}`);
  const rp = path.join(runsDir, `${nowStamp()}_vanity_grind_report.json`);
  fs.writeFileSync(rp, JSON.stringify({ createdAt: new Date().toISOString(), prefix, command: `solana-keygen ${args.join(" ")}`, outputLog: lines }, null, 2));
  ui.ok("Готово / Done");
  ui.info(`Report: ${rp}`);
  ui.info(`RU: Скопируйте выбранный keypair из runs в keypairs/government_token/ (один json-файл).`);
  ui.info(`EN: Copy selected keypair from runs to keypairs/government_token/ (single json file).`);
}
main().catch((e) => { ui.err(`Ошибка / Error: ${e?.message || e}`); process.exit(1); });
