// A standalone x402 v2 client for Speech is Cheap, built on the standard @x402/fetch wrapper.
import { lstat, open, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { pathToFileURL } from 'node:url';
import { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';
import { wrapFetchWithPayment, x402Client, x402HTTPClient } from '@x402/fetch';
import { ExactEvmScheme } from '@x402/evm/exact/client';

const NETWORK = 'eip155:8453';
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
// The first paid response usually reports a pending payment without a job ID. Replaying the same
// proof every few seconds confirms it. An upload purchase must be replayed soon: its 300-second
// upload window starts when the payment is confirmed.
const REPLAY_INTERVAL_MS = 5_000;
const MAX_REPLAYS = 60;
class ExampleError extends Error {}

// The service's own message for an error response, so the failure can be looked up in the docs.
async function detail(response) {
  const text = (await response.text().catch(() => '')).trim();
  try { const { message } = JSON.parse(text); if (typeof message === 'string') return `: ${message}`; } catch { /* Plain text. */ }
  return text ? `: ${text.slice(0, 200)}` : '';
}
// No job ID yet, and the purchase is waiting for payment confirmation or to start.
const pending = result => !result.id && ['PENDING', 'UNCLAIMED'].includes(result.status);

export async function purchase({ body, statePath, maxUsd, signer, fetchImpl = fetch,
  endpoint = 'https://api.speechischeap.com/v2/x402/jobs/', pause = delay, maxReplays = MAX_REPLAYS }) {
  if (!statePath) throw new ExampleError('Choose a state path for this logical purchase.');
  const path = resolve(statePath);
  let lock;
  try { lock = await open(`${path}.lock`, 'wx', 0o600); }
  catch (error) {
    if (error.code === 'EEXIST') throw new ExampleError('State is in use. Inspect its .lock PID; remove only a stale lock after confirming that process stopped.');
    throw error;
  }
  try {
    await lock.writeFile(`${process.pid}\n`);
    let state;
    try {
      const info = await lstat(path);
      if (!info.isFile() || (info.mode & 0o077)) throw new ExampleError('State must be an owner-only regular file.');
      state = JSON.parse(await readFile(path, 'utf8'));
      if (body && (state.body !== JSON.stringify(body) || state.endpoint !== endpoint || state.maxUsd !== maxUsd)) throw new ExampleError('This state belongs to another request. Resume it without changed options.');
    } catch (error) {
      if (error.code !== 'ENOENT') throw error;
      if (!body || !/^\d+(?:\.\d{1,6})?$/.test(maxUsd || '') || Number(maxUsd) <= 0) throw new ExampleError('A new purchase requires request JSON and a positive maxUsd decimal.');
      if (typeof body.input_duration !== 'number' || !Number.isFinite(body.input_duration) || body.input_duration < 6 || body.input_duration > 86_400 || body.can_stream_output) throw new ExampleError('Supply numeric input_duration from 6 to 86400; x402 is asynchronous.');
      const target = new URL(endpoint);
      const local = target.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(target.hostname);
      if (target.username || target.password || (target.protocol !== 'https:' && !local)) throw new ExampleError('Use HTTPS, or localhost for a mock server.');
      state = { endpoint, body: JSON.stringify(body), maxUsd };
      await writeFile(path, JSON.stringify(state), { mode: 0o600, flag: 'wx' });
    }
    const persist = async () => {
      const temporary = `${path}.${process.pid}.tmp`;
      let file;
      try {
        file = await open(temporary, 'wx', 0o600);
        await file.writeFile(JSON.stringify(state));
        await file.sync();
        await file.close();
        file = undefined;
        await rename(temporary, path);
        const directory = await open(dirname(path), 'r');
        try { await directory.sync(); } finally { await directory.close(); }
      } finally {
        await file?.close();
        await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; });
      }
    };
    // Each request gets a new timeout signal, so a long replay loop never reuses an expired one.
    const request = () => ({ method: 'POST', body: state.body, redirect: 'error', signal: AbortSignal.timeout(60_000),
      headers: { 'Content-Type': 'application/json', ...state.paymentHeaders } });
    // Returns the service's JSON for a 2xx response. Any other response throws with advice.
    const accept = async response => {
      if (!response.ok) {
        const header = name => response.headers.get(name);
        if (!state.paymentHeaders) {
          const wait = response.status === 429 ? ` Retry after ${header('Retry-After') || 60} seconds.` : '';
          throw new ExampleError(`HTTP ${response.status}${await detail(response)}. No payment was signed.${wait}`);
        }
        const settlement = response.status === 402 && header('PAYMENT-RESPONSE') ? decodePaymentResponseHeader(header('PAYMENT-RESPONSE')) : null;
        if (response.status === 402 && (header('PAYMENT-REQUIRED') || settlement?.success === false)) {
          // The service rejected this proof or its settlement was declined. It took no payment and
          // never settles this proof later, so the next run signs a new quote.
          const declined = header('PAYMENT-REQUIRED')
            ? `Payment declined: ${decodePaymentRequiredHeader(header('PAYMENT-REQUIRED')).error || 'no reason given'}`
            : `Settlement declined: ${settlement.errorReason || 'no reason given'}`;
          delete state.paymentHeaders;
          await persist();
          throw new ExampleError(`${declined}. No payment was taken. Fix the cause, then run again to sign a new quote.`);
        }
        const reason = `HTTP ${response.status}${await detail(response)}`;
        if ([404, 410].includes(response.status)) throw new ExampleError(`${reason}. No payment was taken. Start a new purchase with a new state path.`);
        throw new ExampleError(`${reason}. Keep this state and replay the same proof.`);
      }
      const result = await response.json();
      state.result = result;
      await persist();
      return result;
    };
    let result;
    if (state.paymentHeaders) {
      // Plain fetch cannot create a replacement payment when the outcome is unknown.
      result = await accept(await fetchImpl(state.endpoint, request()));
    } else {
      if (!signer) throw new ExampleError('Use your configured EVM signer.');
      const client = new x402Client((version, choices) => {
        const accepted = choices.find(choice => version === 2 && choice.scheme === 'exact'
          && choice.network === NETWORK && choice.asset.toLowerCase() === USDC.toLowerCase());
        if (!accepted) throw new ExampleError('Only native USDC on Base mainnet is supported.');
        return accepted;
      }).register(NETWORK, new ExactEvmScheme(signer));
      client.setSpendControls({ maxAmountPerPayment: `$${state.maxUsd}` });
      const http = new x402HTTPClient(client);
      http.onPaymentRequired(async ({ paymentRequired }) => {
        const accepted = paymentRequired.accepts.find(choice => paymentRequired.x402Version === 2 && choice.scheme === 'exact'
          && choice.network === NETWORK && choice.asset.toLowerCase() === USDC.toLowerCase());
        const [whole, fractional = ''] = state.maxUsd.split('.');
        const cap = BigInt(whole) * 1_000_000n + BigInt(fractional.padEnd(6, '0'));
        if (!accepted || !/^\d+$/.test(accepted.amount) || BigInt(accepted.amount) <= 0n || BigInt(accepted.amount) > cap) throw new ExampleError('Quote exceeds the price ceiling or uses an unsupported token/network. No payment was signed.');
      });
      client.onBeforePaymentCreation(async ({ paymentRequired }) => {
        const resource = new URL(paymentRequired.resource.url);
        const expected = new URL(state.endpoint);
        if (resource.origin !== expected.origin || resource.pathname !== expected.pathname || !resource.searchParams.get('purchase_id')) return { abort: true, reason: 'Challenge must bind this endpoint and purchase.' };
      });
      client.onAfterPaymentCreation(async ({ paymentPayload }) => {
        state.paymentHeaders = http.encodePaymentSignatureHeader(paymentPayload);
        await persist(); // Complete before wrapFetchWithPayment sends its paid retry.
      });
      result = await accept(await wrapFetchWithPayment(fetchImpl, http)(state.endpoint, request()));
    }
    // Replay the same request and proof until the payment is confirmed. Replaying never charges again.
    for (let replays = 0; pending(result); replays++) {
      if (replays === maxReplays) throw new ExampleError(`Payment is still pending (${result.payment_status || result.status}). Keep this state and run the same command again to replay the same proof. Never pay again.`);
      await pause(REPLAY_INTERVAL_MS);
      result = await accept(await fetchImpl(state.endpoint, request()));
    }
    // Store the upload secret locally; never print it with the accepted response.
    const { upload_token, ...publicResult } = result;
    return publicResult;
  } finally { await lock.close(); await unlink(`${path}.lock`); }
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  try {
    const [requestPath, statePath, maxUsd] = process.argv.slice(2);
    if (!requestPath || !statePath || !maxUsd) throw new ExampleError('Usage: node x402-client.mjs request.json state.json max-usd; use - for request.json to resume.');
    let signer;
    if (process.env.SIC_X402_WALLET_MODULE) {
      ({ signer } = await import(pathToFileURL(resolve(process.env.SIC_X402_WALLET_MODULE)).href));
    }
    const body = requestPath === '-' ? undefined : JSON.parse(await readFile(requestPath, 'utf8'));
    console.log(JSON.stringify(await purchase({ body, statePath, maxUsd, signer,
      endpoint: process.env.SIC_X402_ENDPOINT || undefined })));
  } catch (error) {
    console.error(error instanceof ExampleError ? error.message : 'Request did not finish. Check request JSON, wallet configuration, and owner-only state permissions; resume the same purchase. Never buy again merely because a response was lost.');
    process.exitCode = 1;
  }
}
