// Node.js 22.13+; npm install @x402/core@2.22.0 @x402/evm@2.22.0 viem@2.55.16
// Default: inspect live payment terms without a wallet or payment.
// --pay: deliberately authorize exactly 0.10 USDC. WEVER_PRIVATE_KEY stays local.
// --retry: resend the saved authorization and exact request, never create another.
import assert from 'node:assert/strict';
import { lstat, open, readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { x402Client } from '@x402/core/client';
import { ExactEvmScheme } from '@x402/evm/exact/client';
import { encodePaymentSignatureHeader, decodePaymentResponseHeader } from '@x402/core/http';
import { privateKeyToAccount } from 'viem/accounts';
import { createPublicClient, http, parseAbi } from 'viem';
import { base } from 'viem/chains';

export const ENDPOINT = 'https://weverlabs.com/mcp';
export const RESOURCE = 'https://weverlabs.com/api/mcp-diligence-rail';
export const TOOL = 'wever_mcp-diligence-rail';
export const NETWORK = 'eip155:8453';
export const ASSET = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
export const PAY_TO = '0xc3837428F0e36E2573025c4A22E0F774FB3Cee3e';
export const AMOUNT = '100000'; // USDC has six decimals: exactly 0.10 USDC.
export const BODY = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call',
  params: { name: TOOL, arguments: { tools: [{ name: 'read', annotations: { readOnlyHint: true } }] } } });
const DEFAULT_CHECKPOINT = '.wever-first-paid-call.json';
const sameAddress = (a, b) => typeof a === 'string' && typeof b === 'string' && a.toLowerCase() === b.toLowerCase();

async function readLiveBalance(address) {
  const chain = createPublicClient({ chain: base,
    transport: http('https://mainnet.base.org', { retryCount: 0, timeout: 15000 }) });
  assert.equal(await chain.getChainId(), 8453, 'Unexpected funding-check network');
  return chain.readContract({ address: ASSET, abi: parseAbi(['function balanceOf(address) view returns (uint256)']),
    functionName: 'balanceOf', args: [address] });
}

export function validateTerms(terms) {
  assert.equal(terms?.x402Version, 2, 'Expected x402 v2');
  assert.equal(terms?.resource?.url, RESOURCE, 'Unexpected payment resource');
  assert.equal(terms?.accepts?.length, 1, 'Expected one exact payment option');
  const price = terms.accepts[0];
  assert.equal(price.scheme, 'exact', 'Unexpected payment scheme');
  assert.equal(price.network, NETWORK, 'Expected Base mainnet');
  assert.equal(price.amount, AMOUNT, 'Refusing any price other than 0.10 USDC');
  assert(sameAddress(price.asset, ASSET), 'Unexpected USDC contract');
  assert(sameAddress(price.payTo, PAY_TO), 'Unexpected settlement address');
  assert.equal(price.extra?.name, 'USD Coin', 'Unexpected token signing domain');
  assert.equal(price.extra?.version, '2', 'Unexpected token signing version');
  assert(Number.isInteger(price.maxTimeoutSeconds) && price.maxTimeoutSeconds > 0 && price.maxTimeoutSeconds <= 120,
    'Unexpected authorization lifetime');
  return price;
}

function validateCheckpoint(state) {
  assert.equal(state?.version, 1, 'Unsupported checkpoint');
  assert.equal(state.body, BODY, 'Checkpoint request differs; do not replace a pending payment');
  const payload = state.payload;
  validateTerms({ x402Version: payload?.x402Version, resource: payload?.resource, accepts: [payload?.accepted] });
  const auth = payload?.payload?.authorization;
  assert(/^0x[0-9a-fA-F]{40}$/.test(state.payer), 'Invalid checkpoint payer');
  assert(sameAddress(auth?.from, state.payer) && sameAddress(auth?.to, PAY_TO), 'Unexpected authorization parties');
  assert.equal(auth?.value, AMOUNT, 'Unexpected authorization amount');
  assert(/^0x[0-9a-fA-F]{64}$/.test(auth?.nonce), 'Invalid authorization nonce');
  assert(typeof payload.payload.signature === 'string', 'Missing payment signature');
  return state;
}

async function loadCheckpoint(path) {
  const info = await lstat(path);
  assert(info.isFile() && !info.isSymbolicLink(), 'Checkpoint must be a regular private file');
  assert((info.mode & 0o077) === 0, 'Checkpoint must be private: chmod 600 the file');
  return validateCheckpoint(JSON.parse(await readFile(path, 'utf8')));
}

async function saveCheckpoint(path, state) {
  // Exclusive creation also refuses existing files and symbolic links.
  const file = await open(path, 'wx', 0o600);
  try { await file.writeFile(JSON.stringify(state)); await file.sync(); }
  finally { await file.close(); }
}

async function call(fetchImpl, body, signature) {
  const headers = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream',
    'MCP-Protocol-Version': '2025-11-25' };
  if (signature) headers['Payment-Signature'] = signature;
  const response = await fetchImpl(ENDPOINT, { method: 'POST', headers, body,
    redirect: 'error', signal: AbortSignal.timeout(45000) });
  assert.equal(response.status, 200, 'MCP transport failed; if payment was sent, retain the checkpoint');
  const envelope = await response.json();
  assert(!envelope.error && envelope.result?.structuredContent, 'Missing MCP tool result');
  const result = envelope.result.structuredContent;
  assert.equal(result.product, 'mcp-diligence-rail', 'Unexpected result product');
  assert.equal(result.api_path, '/api/mcp-diligence-rail', 'Unexpected result route');
  return result;
}

// An agent may inject its existing account signer. Neither the key nor signed
// authorization is included in console output. This function never funds a wallet.
export async function run({ mode = 'challenge', account, checkpointPath = DEFAULT_CHECKPOINT,
  fetchImpl = fetch, readBalance = readLiveBalance,
  print = value => console.log(JSON.stringify(value, null, 2)) } = {}) {
  assert(['challenge', 'pay', 'retry'].includes(mode), 'Use challenge, pay or retry');
  const checkpoint = resolve(checkpointPath);
  let state;
  if (mode === 'retry') {
    state = await loadCheckpoint(checkpoint);
  } else {
    const challenge = await call(fetchImpl, BODY);
    assert.equal(challenge.backend_status, 402, 'Expected nested backend 402');
    const terms = challenge.body, price = validateTerms(terms);
    print({ stage: 'payment_required', mcp_http_status: 200, backend_status: 402,
      resource: terms.resource.url, network: price.network, amount_atomic: price.amount,
      asset: price.asset, pay_to: price.payTo });
    if (mode === 'challenge') return { status: 'challenge_only', challenge };
    assert(account?.address && typeof account.signTypedData === 'function', 'A funded account signer is required for --pay');
    // Check before signing. Never silently replace a saved authorization.
    try { await lstat(checkpoint); throw new Error('Checkpoint exists. Use --retry; do not create another payment.'); }
    catch (error) { if (error.code !== 'ENOENT') throw error; }
    // Read the existing wallet balance before creating any payment authorization.
    const balance = BigInt(await readBalance(account.address));
    assert(balance >= 0n, 'Unexpected wallet balance');
    if (balance < BigInt(AMOUNT)) {
      const stopped = { status: 'not_signed', stage: 'insufficient_funds', network: NETWORK,
        wallet: account.address, balance_atomic: String(balance), required_atomic: AMOUNT,
        signatures_created: 0, payments_submitted: 0 };
      print(stopped);
      return stopped;
    }
    const client = new x402Client().register(NETWORK, new ExactEvmScheme(account));
    const payload = await client.createPaymentPayload(terms);
    state = validateCheckpoint({ version: 1, payer: account.address, body: BODY, payload });
    await saveCheckpoint(checkpoint, state);
  }
  // Intentionally omit X-Wever-Wallet-Proof: this demonstration chooses paid
  // access directly. It does not consume the shared signed-wallet free allowance.
  const result = await call(fetchImpl, state.body, encodePaymentSignatureHeader(state.payload));
  const paymentStatus = result.payment?.['x-wever-payment-status'];
  if (result.backend_status !== 200 || !['settled', 'settled_replay', 'settled_recovered'].includes(paymentStatus)) {
    print({ stage: 'payment_not_confirmed', backend_status: result.backend_status,
      payment_status: paymentStatus ?? null, result: result.body,
      next: 'Keep the private checkpoint. Use --retry with the same authorization. Do not create a replacement payment.' });
    return { status: 'payment_not_confirmed', result };
  }
  const receipt = decodePaymentResponseHeader(result.payment['payment-response']);
  assert(receipt.success && receipt.network === NETWORK && /^0x[0-9a-fA-F]{64}$/.test(receipt.transaction),
    'Settlement receipt is invalid; retain the checkpoint');
  assert(sameAddress(receipt.payer, state.payer), 'Settlement payer differs; retain the checkpoint');
  print({ stage: 'paid_call_complete', backend_status: result.backend_status, payment_status: paymentStatus,
    amount_atomic: AMOUNT, network: NETWORK, transaction: receipt.transaction,
    explorer: 'https://basescan.org/tx/' + receipt.transaction, result: result.body });
  return { status: 'paid_call_complete', result, receipt };
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  try {
    const args = process.argv.slice(2);
    assert(args.length <= 1 && args.every(arg => ['--pay', '--retry'].includes(arg)), 'Usage: node first-paid-call.mjs [--pay|--retry]');
    const mode = args[0] === '--pay' ? 'pay' : args[0] === '--retry' ? 'retry' : 'challenge';
    const account = mode === 'pay' ? privateKeyToAccount(process.env.WEVER_PRIVATE_KEY ?? '') : undefined;
    const result = await run({ mode, account });
    if (['payment_not_confirmed', 'not_signed'].includes(result.status)) process.exitCode = 1;
  } catch {
    // Avoid SDK error objects: they can include private keys or authorizations.
    console.error('Quickstart stopped. Check dependencies, arguments, wallet funding and the private checkpoint. If payment may have been sent, keep the checkpoint and use --retry; never create a replacement authorization.');
    process.exitCode = 1;
  }
}
