#!/usr/bin/env node
// AnyGas PLUS pass wallet — encrypted-at-rest storage for bearer passes, as a library AND a CLI.
// Passes are cash: whoever holds {preparedMsg, sig} can spend it. So they live in ONE file, encrypted with
// AES-256-GCM under a scrypt-derived key (passphrase from PLUS_WALLET_PASS or --pass), written atomically,
// and each spend removes the pass before it is sent so a crash cannot double-spend or leak a spent pass.
//
//   library:  import { openWallet } from './plus-wallet.mjs';
//             const w = await openWallet('./passes.enc', process.env.PLUS_WALLET_PASS);
//             w.add(await plus.trial()); const pass = w.take(); await w.save();
//   CLI:      node plus-wallet.mjs trial                 # 20 free passes/day into the wallet
//             node plus-wallet.mjs buy eth-8453 [bundles] # prints invoice; then: claim <invoiceId> <txHash>
//             node plus-wallet.mjs claim <invoiceId> <txHash>
//             node plus-wallet.mjs balance | take | cover | anchor <rowId>
//   env:      PLUS_WALLET=./passes.enc  PLUS_WALLET_PASS=...  ANYGAS_BASE=https://anygas.xyz
// Dependencies: the same as plus-sdk.mjs (ethers, @cloudflare/blindrsa-ts). Nothing phones home except the calls you ask for.
import crypto from 'node:crypto';
import { readFileSync, writeFileSync, renameSync, existsSync } from 'node:fs';

const MAGIC = 'anygas-plus-wallet-v1';
function kdf(pass, salt) { return crypto.scryptSync(String(pass), salt, 32, { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }); }
function encrypt(obj, pass) {
  const salt = crypto.randomBytes(16), nonce = crypto.randomBytes(12), key = kdf(pass, salt);
  const c = crypto.createCipheriv('aes-256-gcm', key, nonce);
  const ct = Buffer.concat([c.update(Buffer.from(JSON.stringify(obj), 'utf8')), c.final()]);
  return JSON.stringify({ magic: MAGIC, kdf: 'scrypt-n15', salt: salt.toString('base64'), nonce: nonce.toString('base64'), tag: c.getAuthTag().toString('base64'), ct: ct.toString('base64') });
}
function decrypt(text, pass) {
  const j = JSON.parse(text); if (j.magic !== MAGIC) throw new Error('not a plus wallet file');
  const key = kdf(pass, Buffer.from(j.salt, 'base64'));
  const d = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(j.nonce, 'base64')); d.setAuthTag(Buffer.from(j.tag, 'base64'));
  return JSON.parse(Buffer.concat([d.update(Buffer.from(j.ct, 'base64')), d.final()]).toString('utf8'));
}

export async function openWallet(path, pass) {
  if (!pass) throw new Error('wallet passphrase required (PLUS_WALLET_PASS)');
  let state = { passes: [], spent: 0, created: new Date().toISOString() };
  if (existsSync(path)) state = decrypt(readFileSync(path, 'utf8'), pass);
  const save = async () => { const tmp = path + '.tmp'; writeFileSync(tmp, encrypt(state, pass), { mode: 0o600 }); renameSync(tmp, path); };
  return {
    count: () => state.passes.length,
    add: (passes) => { for (const p of passes || []) if (p && p.preparedMsg && p.sig) state.passes.push({ preparedMsg: p.preparedMsg, sig: p.sig }); return state.passes.length; },
    /// Remove and return one pass. Call save() BEFORE sending it, so a crash mid-request cannot reuse it.
    take: () => { const p = state.passes.shift(); if (p) state.spent++; return p || null; },
    /// Convenience: take + save in one step (the safe order).
    takeSaved: async () => { const p = state.passes.shift(); if (p) { state.spent++; await save(); } return p || null; },
    stats: () => ({ available: state.passes.length, spent: state.spent, created: state.created }),
    save,
  };
}

// ---------- CLI ----------
if (import.meta.url === 'file://' + process.argv[1] || (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/')))) {
  const [cmd, ...rest] = process.argv.slice(2);
  const path = process.env.PLUS_WALLET || './passes.enc';
  const passIdx = rest.indexOf('--pass'); const pass = passIdx >= 0 ? rest.splice(passIdx, 2)[1] : process.env.PLUS_WALLET_PASS;
  const plus = await import('./plus-sdk.mjs').catch(() => import('https://anygas.xyz/svc/plus-sdk.mjs'));
  const w = await openWallet(path, pass);
  const out = (o) => console.log(typeof o === 'string' ? o : JSON.stringify(o, null, 2));
  try {
    switch (cmd) {
      case 'balance': out(w.stats()); break;
      case 'trial': { const ps = await plus.trial(); w.add(ps); await w.save(); out({ added: ps.length, ...w.stats() }); break; }
      case 'buy': { const inv = await plus.invoice({ asset: rest[0] || 'eth-8453', bundles: Number(rest[1] || 1), refundAddress: rest[2] }); out({ ...inv, then: 'pay, then: plus-wallet claim ' + inv.invoiceId + ' <txHash>' }); break; }
      case 'claim': { const ps = await plus.claim(rest[0], rest[1]); w.add(ps); await w.save(); out({ added: ps.length, ...w.stats() }); break; }
      case 'take': { const p = await w.takeSaved(); out(p || 'wallet empty'); break; }
      case 'cover': { const p = await w.takeSaved(); out(p ? await plus.fundCover(p) : 'wallet empty'); break; }
      case 'anchor': { const p = await w.takeSaved(); out(p ? await plus.anchor(p, rest[0]) : 'wallet empty'); break; }
      default: out('usage: plus-wallet <balance|trial|buy <asset> [bundles] [btcRefund]|claim <invoiceId> <txHash>|take|cover|anchor <rowId>> [--pass ...]');
    }
  } catch (e) { console.error('error:', e.message, e.body ? JSON.stringify(e.body) : ''); process.exit(1); }
}
