// AnyGas PLUS SDK — buy unlinkable passes with crypto; spend them on capacity, funded cover, anchoring.
// Node 18+ ESM. Dependencies: npm i ethers @cloudflare/blindrsa-ts
//
//   import * as plus from 'https://anygas.xyz/svc/plus-sdk.mjs';
//   const inv = await plus.invoice({ asset: 'eth-8453' });            // {invoiceId, payTo, amount, human}
//   const tx = await wallet.sendTransaction({ to: inv.payTo, value: BigInt(inv.amount) }); await tx.wait();
//   const passes = await plus.claim(inv.invoiceId, tx.hash);          // 500 unlinkable {preparedMsg, sig}
//   // store `passes` locally (they are bearer tokens); spend one per privileged action:
//   await msg2.send('sphynx.robynchain.eth', 'gm', { wallet, pass: passes.pop() });
//
// Why this is private: we blind each token before the server signs it (RFC 9474). The server sees a
// payment and N opaque blobs; when a pass is later redeemed it cannot tell which payment — or which other
// pass — it came from. A pass is not an account.
import crypto from 'node:crypto';
import { RSABSSA } from '@cloudflare/blindrsa-ts';

export const BASE = process.env.ANYGAS_BASE || 'https://anygas.xyz';
export const TOKEN_PREFIX = 'robyn-plus-v1:';
const suite = RSABSSA.SHA384.PSS.Randomized();
const b64 = (u8) => Buffer.from(u8).toString('base64');
const unb64 = (s) => Uint8Array.from(Buffer.from(String(s || ''), 'base64'));

async function api(path, opts = {}) {
  const r = await fetch(BASE + path, { ...opts, headers: { 'content-type': 'application/json', ...(opts.headers || {}) }, body: opts.body ? JSON.stringify(opts.body) : undefined });
  const j = await r.json().catch(() => ({}));
  if (!r.ok) throw Object.assign(new Error(j.error || ('HTTP ' + r.status)), { status: r.status, body: j });
  return j;
}
export const info = () => api('/api/plus/info');
export const invoiceStatus = (id) => api('/api/plus/invoice/' + encodeURIComponent(id));

let _pub = null;
export async function publicKey() {
  if (_pub) return _pub;
  const i = await info();
  if (!i.tokens || !i.tokens.publicKeyJwk) throw new Error('plus is not enabled on this deployment');
  const { webcrypto } = await import('node:crypto');
  _pub = await webcrypto.subtle.importKey('jwk', i.tokens.publicKeyJwk, { name: 'RSA-PSS', hash: 'SHA-384' }, true, ['verify']);
  return _pub;
}

/// Create an invoice. asset: eth-4663 | eth-1 | eth-42161 | eth-8453 | usdc-8453 | usdc-42161 | btc (btc needs refundAddress).
export const invoice = ({ bundle = 'bundle', asset, refundAddress } = {}) => api('/api/plus/invoice', { method: 'POST', body: { bundle, asset, refundAddress } });

/// Prepare + blind `n` fresh tokens locally. Keep the returned `secrets` until claim() finalises them.
export async function blindTokens(n) {
  const pub = await publicKey(); const enc = new TextEncoder(); const out = [];
  for (let i = 0; i < n; i++) {
    const msg = TOKEN_PREFIX + crypto.randomBytes(16).toString('hex');
    const prepared = suite.prepare(enc.encode(msg));
    const { blindedMsg, inv } = await suite.blind(pub, prepared);
    out.push({ prepared, inv, blindedMsg });
  }
  return out;
}

/// After paying: submit blinded tokens, receive blind signatures, finalise into spendable passes.
/// Returns [{preparedMsg, sig}] (base64) — bearer tokens; store them like cash.
export async function claim(invoiceId, txHash, { count, headers, simulatePayment } = {}) {
  const st = await invoiceStatus(invoiceId);
  const n = Math.min(count || st.remainingTokens || st.tokens || 0, st.remainingTokens ?? Infinity);
  if (!(n > 0)) throw new Error('nothing left to claim on this invoice');
  const pub = await publicKey();
  const t = await blindTokens(n);
  const r = await api('/api/plus/claim', { method: 'POST', headers, body: { invoiceId, txHash, blinded: t.map((x) => b64(x.blindedMsg)), ...(simulatePayment ? { simulatePayment: true } : {}) } });
  const passes = [];
  for (let i = 0; i < r.blindSigs.length; i++) {
    const sig = await suite.finalize(pub, t[i].prepared, unb64(r.blindSigs[i]), t[i].inv);
    if (!(await suite.verify(pub, sig, t[i].prepared))) throw new Error('server returned an invalid blind signature');
    passes.push({ preparedMsg: b64(t[i].prepared), sig: b64(sig) });
  }
  return passes;
}

/// Free trial: up to 20 passes per day per caller, no payment. Identical unlinkable passes.
export async function trial({ count = 20, headers } = {}) {
  const pub = await publicKey(); const t = await blindTokens(count);
  const r = await api('/api/plus/trial', { method: 'POST', headers, body: { blinded: t.map((x) => b64(x.blindedMsg)) } });
  const passes = [];
  for (let i = 0; i < r.blindSigs.length; i++) { const sig = await suite.finalize(pub, t[i].prepared, unb64(r.blindSigs[i]), t[i].inv); if (await suite.verify(pub, sig, t[i].prepared)) passes.push({ preparedMsg: b64(t[i].prepared), sig: b64(sig) }); }
  return passes;
}
/// Spend a pass on funded cover (one extra cover row within 24 h) or anchoring (one feed row id).
export const fundCover = (pass, headers) => api('/api/messages/v2/plus/cover', { method: 'POST', headers, body: { pass } });
export const anchor = (pass, id, headers) => api('/api/messages/v2/plus/anchor', { method: 'POST', headers, body: { pass, id } });
export const anchorProof = (id) => api('/api/messages/v2/anchor/' + encodeURIComponent(id));
export const erasure = () => api('/api/messages/v2/erasure');

/// Verify an anchor proof locally (sha256 Merkle + EIP-191 signature by the published signer).
export async function verifyAnchorProof(pr) {
  const { ethers } = await import('ethers');
  const sha = (b) => crypto.createHash('sha256').update(b).digest();
  let h = Buffer.from(pr.leaf, 'hex');
  for (const st of pr.path) { const sb = Buffer.from(st.hash, 'hex'); h = sha(st.right ? Buffer.concat([h, sb]) : Buffer.concat([sb, h])); }
  const rootOk = h.toString('hex') === pr.root;
  const leafOk = sha(Buffer.from('robyn-msg2-anchor-v1:' + pr.id, 'utf8')).toString('hex') === pr.leaf;
  let sigOk = false; try { sigOk = ethers.verifyMessage(pr.message, pr.signature).toLowerCase() === String(pr.signer).toLowerCase() && pr.message.includes('root: ' + pr.root); } catch {}
  return { ok: rootOk && leafOk && sigOk, rootOk, leafOk, sigOk, onchain: pr.onchain || null };
}
