// Black_Wall — your first SETTLED call, in one command.
//
//   npm i viem @x402/fetch @x402/evm
//   node first-settled-call.mjs                 (add --dry-run to stop before paying)
//
// Verdicts for payments under $10 at risk are FREE (no wallet, no payment — see the
// quickstart). This script is the other half: a REAL x402-settled call, so you get a
// verdict AND a third-party-verifiable receipt, and the oracle's moat gets its first
// real datum from you. It settles ~$0.01 USDC on Base (10bps of a $10.01 forecast —
// the cheapest a payable call can be above the free floor). No MetaMask, no key copying.
//
// What it does:
//   1. Creates (or reuses) a local burner wallet in burner-wallet.json — never leaves
//      this machine, holds at most ~$1.
//   2. Prints the burner ADDRESS and waits while you send ~$1 USDC to it on BASE
//      (Coinbase: Send -> USDC -> paste address -> network: Base). Polls, continues itself.
//   3. Pays ~$0.01 via x402 and prints your verdict + signed receipt. A fresh/unknown
//      counterparty gets HOLD — the oracle refusing to invent trust from silence.
//
// The receipt is an Ed25519 signature over (verdict, counterparty, amount, receipt_id, ts).
// Verify it against the published key with ANY RFC 8032 library, Black_Wall out of the loop:
//   key: https://agent-egress-proxy.onrender.com/.well-known/blackwall-receipt-key.json
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { createInterface } from 'node:readline/promises';
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
import { createPublicClient, http, formatUnits } from 'viem';
import { base } from 'viem/chains';
import { wrapFetchWithPaymentFromConfig } from '@x402/fetch';
import { ExactEvmScheme } from '@x402/evm';

const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const ORACLE = 'https://agent-egress-proxy.onrender.com/v1/forecast-payment';
const KEY_URL = 'https://agent-egress-proxy.onrender.com/.well-known/blackwall-receipt-key.json';
const WALLET_FILE = new URL('./burner-wallet.json', import.meta.url);
const DRY_RUN = process.argv.includes('--dry-run');

// The address you are ABOUT to pay. Default is a neutral probe (the USDC contract);
// replace with the real payTo from your 402 to get a verdict about YOUR actual payment.
const COUNTERPARTY = process.env.BW_COUNTERPARTY || USDC;

// ---- 1. burner wallet: create once, reuse forever ----
let key;
if (existsSync(WALLET_FILE)) {
  key = JSON.parse(readFileSync(WALLET_FILE, 'utf8')).privateKey;
  console.log('Using your existing burner wallet (burner-wallet.json).');
} else {
  key = generatePrivateKey();
  writeFileSync(WALLET_FILE, JSON.stringify({
    WARNING: 'Private key for a THROWAWAY wallet. Never put more than ~$1 in it. Never share this file.',
    privateKey: key, created: new Date().toISOString(),
  }, null, 2));
  console.log('Created a fresh burner wallet -> burner-wallet.json (keep it, or delete to start over).');
}
const account = privateKeyToAccount(key);
console.log(`\nYour burner ADDRESS (safe to share): ${account.address}\n`);

// ---- 2. wait for funding ----
const chain = createPublicClient({ chain: base, transport: http('https://mainnet.base.org') });
const balanceOf = async () => chain.readContract({
  address: USDC, abi: [{ name: 'balanceOf', type: 'function', stateMutability: 'view',
    inputs: [{ name: 'a', type: 'address' }], outputs: [{ type: 'uint256' }] }],
  functionName: 'balanceOf', args: [account.address],
});
let bal = await balanceOf();
if (bal < 20_000n) { // < 0.02 USDC — must cover the ~$0.01001 fee comfortably
  console.log('It needs ~$1 of USDC on the BASE network. From Coinbase:');
  console.log('  Send -> USDC -> paste the address above -> NETWORK: Base (important!) -> send $1');
  console.log('\nWaiting for the money to arrive (every 15s, Ctrl+C to quit)...');
  while (bal < 20_000n) {
    await new Promise((r) => setTimeout(r, 15_000));
    bal = await balanceOf();
    process.stdout.write('.');
  }
  console.log('');
}
console.log(`Funded: ${formatUnits(bal, 6)} USDC on Base.`);

// ---- 3. the settled call ----
if (DRY_RUN) { console.log('\n--dry-run: stopping before payment. Everything up to the payment works.'); process.exit(0); }
const rl = createInterface({ input: process.stdin, output: process.stdout });
await rl.question('\nPress Enter to settle ~$0.01 USDC for your first verdict (Ctrl+C to cancel)... ');
rl.close();

const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
  schemes: [{ network: 'eip155:8453', client: new ExactEvmScheme(account) }],
});
const res = await fetchWithPayment(ORACLE, {
  method: 'POST', headers: { 'content-type': 'application/json' },
  body: JSON.stringify({
    counterparty: COUNTERPARTY,
    amount: '10.01', asset: 'USDC', chain: 'base', // > $10 free floor, so it actually settles
    payer: account.address, resource: 'first-settled-call',
  }),
});

console.log(`\nHTTP ${res.status}`);
const body = await res.text();
try {
  const v = JSON.parse(body);
  console.log(`\nVERDICT: ${v.verdict}  (score ${v.score})`);
  for (const r of v.reasons ?? []) console.log(`  - ${r}`);
  if (v.receipt_id) console.log(`\nreceipt_id: ${v.receipt_id}`);
  if (v.signed_receipt) {
    console.log('signed_receipt (Ed25519, third-party verifiable):');
    console.log('  ' + JSON.stringify(v.signed_receipt));
    console.log(`\nVerify it yourself — the key is public, we are out of the loop:`);
    console.log(`  key: ${KEY_URL}`);
    console.log('  check the sig over the canonical fields with any RFC 8032 library.');
  }
  if (v.verdict === 'HOLD') {
    console.log('\nA HOLD on a fresh/unknown counterparty is the oracle WORKING: no history');
    console.log('means no trust — it will not rubber-stamp a stranger, not even for you.');
  }
} catch { console.log(body); }
console.log(res.ok ? '\nDone. Your key stays in burner-wallet.json; your change stays in the burner.'
                   : '\nSomething went wrong — share this output for help.');
