/**
 * GET /api/x402/trust/health
 *
 * Free discovery beacon — no payment required.
 * Designed for x402 crawlers, agent-directory bots, and humans previewing
 * the service before paying. Returns rich metadata so crawlers can index
 * what we offer without spending USDC.
 */

import { NextRequest, NextResponse } from 'next/server';
import { checkRateLimit, RATE_LIMIT_GET } from '../../../../lib/rate-limit';

const PAY_TO = (process.env.PAY_TO_ADDRESS || '0xfA15Ee28939B222B0448261A22156070f0A7813C').trim();

export async function GET(req: NextRequest) {
  const rateLimitResponse = checkRateLimit(req, RATE_LIMIT_GET);
  if (rateLimitResponse) return rateLimitResponse;

  let hubHealth: Record<string, unknown> = { status: 'unreachable' };
  let hubStats: Record<string, unknown> = {};

  try {
    const hubUrl = `${req.nextUrl.origin}/api/health`;
    const hubRes = await fetch(hubUrl, { signal: AbortSignal.timeout(5000) });
    hubHealth = await hubRes.json();
  } catch {
    // Hub unreachable — still return our own health
  }

  try {
    const statsUrl = `${req.nextUrl.origin}/api/hub/stats`;
    const statsRes = await fetch(statsUrl, { signal: AbortSignal.timeout(5000) });
    hubStats = await statsRes.json();
  } catch {
    // Stats unreachable — still return discovery metadata
  }

  return NextResponse.json({
    // ===== Identity =====
    service: 'vaultfire-trust-x402',
    name: 'Vaultfire Trust Service',
    description:
      "On-chain trust infrastructure for AI agents — full Vaultfire surface area as priced x402 endpoints. ERC-8004 identity, bond status, reputation, validation, dispute, insurance, credential, VNS, mission/surveillance enforcement, trustless USDC task escrow, ERC-5192 soulbound Street Cred badges, ERC-7702 session keys, VKP vaults, scoped delegation, SLA enforcement, multisig governance, cross-chain trust bridge, and Chainlink price oracle integration (15 Data Feeds across 4 chains, with USD-denominated agent stake composition). 73 endpoints (71 priced + 2 free) across Base, Avalanche, Arbitrum, and Polygon. Read endpoints accept USDC on Base AND Solana mainnet. The trust layer for the agentic web.",
    status: 'ok',
    version: 6,
    endpointCount: 73,
    pricedEndpointCount: 71,

    // ===== Categorization (helps directory indexers) =====
    category: 'trust-and-identity',
    subcategory: 'agent-reputation',
    tags: [
      'erc-8004',
      'agent-identity',
      'reputation',
      'trust-score',
      'on-chain',
      'multichain',
      'bonds',
      'kya',
      'a2a',
      'vns',
      'validation',
      'dispute',
      'insurance',
      'credentials',
      'mission-enforcement',
      'anti-surveillance',
      'post-quantum',
      'task-escrow',
      'task-marketplace',
      'street-cred',
      'soulbound',
      'erc-5192',
      'session-keys',
      'vkp',
      'commit-reveal',
      'decay',
      'safety-manager',
      'sla-enforcer',
      'scoped-delegation',
      'flourishing-metrics',
      'multisig',
      'cross-chain-bridge',
    ],
    standards: ['ERC-8004', 'ERC-8128', 'ERC-7702', 'ERC-5192', 'ERC-4626', 'EIP-712', 'XMTP-V3'],
    chains: ['base', 'avalanche', 'arbitrum', 'polygon'],

    // ===== Protocol =====
    protocol: 'x402',
    bazaar: true,
    facilitator: 'cdp',
    facilitatorUrl: 'https://api.cdp.coinbase.com/platform/v2/x402',
    payTo: PAY_TO,
    payToVns: 'agent-fa15.vns',
    payToSolana: '6KpXaFmaR8WPWr79qzsMBvwDbDzYFErwNoWxfwqDr8JU',
    // Primary network (kept for Bazaar/x402 directory aggregators that expect a
    // single `network` field). The full list of accepted networks is below in
    // `networks` (plural) and per-endpoint in `paymentNetworks`.
    network: 'eip155:8453',
    networks: ['eip155:8453', 'solana'],
    accepts: ['USDC'],
    paymentNetworks: {
      reads: {
        // 24 priced GET endpoints accept USDC on Base AND Solana mainnet.
        // Server verifies SPL transfer signature on Solana RPC.
        endpointCount: 24,
        networks: ['eip155:8453', 'solana'],
        usdc: {
          base: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
          solana: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
        },
        payTo: {
          base: PAY_TO,
          solana: '6KpXaFmaR8WPWr79qzsMBvwDbDzYFErwNoWxfwqDr8JU',
        },
      },
      actions: {
        // 45 priced POST tx-prepare endpoints currently accept USDC on Base only.
        // Solana support pending x402-next multi-network route config.
        endpointCount: 45,
        networks: ['eip155:8453'],
        usdc: {
          base: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
        },
        payTo: {
          base: PAY_TO,
        },
      },
    },

    // ===== Discovery surfaces =====
    discovery: {
      x402Manifest: 'https://theloopbreaker.com/.well-known/x402.json',
      agentCard: 'https://theloopbreaker.com/.well-known/agent-card.json',
      llmsTxt: 'https://theloopbreaker.com/llms.txt',
      skill: 'https://theloopbreaker.com/SKILL.md',
      docs: 'https://theloopbreaker.com',
      github: 'https://github.com/Ghostkey316/ghostkey-316-vaultfire-init',
    },

    // ===== Endpoints (free preview of what's behind the paywall) =====
    endpoints: {
      // ----- GET reads (22 priced + 1 free) -----
      agentStatus: {
        path: '/api/x402/trust/agent-status',
        price: '$0.01 USDC',
        method: 'GET',
        description:
          "Look up any AI agent's on-chain trust profile — ERC-8004 registration, bond count, trust score (0–95), VNS name, and explorer link.",
        params: ['address (required)', 'chain (base|avalanche|arbitrum|polygon, default: base)'],
      },
      protocolStats: {
        path: '/api/x402/trust/protocol-stats',
        price: '$0.01 USDC',
        method: 'GET',
        description: 'Protocol-wide statistics — registered agents, active bonds, per-chain breakdown.',
      },
      contracts: {
        path: '/api/x402/trust/contracts',
        price: '$0.05 USDC',
        method: 'GET',
        description: 'Full address book of 134 deployed Vaultfire contracts across all 4 chains.',
      },
      bonds: {
        path: '/api/x402/trust/bonds',
        price: '$0.01 USDC',
        method: 'GET',
        description: 'Active partnership bonds for any agent — bond count, partner addresses, locked stake.',
        params: ['address (required)'],
      },
      insurance: {
        path: '/api/x402/trust/insurance',
        price: '$0.01 USDC',
        method: 'GET',
        description: 'Insurance pool stats per chain — balance, contributors, claims, paid out.',
        params: ['chain (default: base)'],
      },
      disputes: {
        path: '/api/x402/trust/disputes',
        price: '$0.01 USDC',
        method: 'GET',
        description: 'Dispute resolution stats per chain — filed, resolved, total stake at risk.',
        params: ['chain (default: base)'],
      },
      performance: {
        path: '/api/x402/trust/performance',
        price: '$0.01 USDC',
        method: 'GET',
        description: 'Trust oracle performance — attestations, quality score, task completions.',
        params: ['address (required)', 'chain (default: base)'],
      },
      vouching: {
        path: '/api/x402/trust/vouching',
        price: '$0.01 USDC',
        method: 'GET',
        description: 'Reputation staking profile — vouches received/given, total stake, slashes.',
        params: ['address (required)', 'chain (default: base)'],
      },
      credentials: {
        path: '/api/x402/trust/credentials',
        price: '$0.01 USDC',
        method: 'GET',
        description: 'Capability credentials — total credentials, active credentials, task proofs.',
        params: ['address (required)', 'chain (default: base)'],
      },
      bridge: {
        path: '/api/x402/trust/bridge',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Cross-chain bridge state — message counts, paused, relayer count, synced totals.',
        params: ['chain (default: base)'],
      },
      analytics: {
        path: '/api/x402/trust/analytics',
        price: '$0.05 USDC',
        method: 'GET',
        description: 'Composite trust profile — Street Cred, identity, bonds, reputation in one call.',
        params: ['address (required)', 'chain (default: base)'],
      },
      contractCall: {
        path: '/api/x402/contract-call',
        price: '$0.01 USDC',
        method: 'POST | GET',
        description: 'Generic on-chain read against any of the 134 Vaultfire contracts. Pass { chain, contract, function, args } and receive the decoded return value plus block provenance. Read-only (view/pure) only.',
        params: ['chain', 'contract (name or 0x-address)', 'function', 'args[]'],
      },
      vnsResolve: {
        path: '/api/x402/trust/vns-resolve',
        price: '$0.01 USDC',
        method: 'GET',
        description: 'Resolve VNS names to addresses (forward) or addresses to VNS names (reverse). Falls back to ERC-8004 identity registry.',
        params: ['name OR address (one required)', 'chain (default: base)'],
      },
      multiChainStatus: {
        path: '/api/x402/trust/multi-chain-status',
        price: '$0.03 USDC',
        method: 'GET',
        description: "Aggregate an agent's on-chain status across all 4 chains in a single call.",
        params: ['address (required)'],
      },
      leaderboard: {
        path: '/api/x402/trust/leaderboard',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Top AI agents ranked by trust score — live ERC-8004 enumeration + scoring.',
        params: ['limit (default 20, max 100)', 'chain (optional filter)'],
      },
      relationships: {
        path: '/api/x402/trust/relationships',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Vouching graph slice for an agent — vouches given/received, slashes, partnerships.',
        params: ['address (required)', 'chain (default: base)'],
      },
      history: {
        path: '/api/x402/trust/history',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Trust history timeline assembled from on-chain state.',
        params: ['address (required)', 'chain (default: base)'],
      },
      riskScore: {
        path: '/api/x402/trust/risk-score',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Composite 0–100 risk score with band (minimal/low/medium/high).',
        params: ['address (required)', 'chain (default: base)'],
      },

      // ----- POST tx-prepare actions (22 priced) -----
      registerAgent: {
        path: '/api/x402/actions/register-agent',
        price: '$0.50 USDC',
        method: 'POST',
        description: 'Tx-prepare for ERC-8004 agent registration. Returns unsigned transaction; caller signs in wallet. No private keys handled.',
        params: ['name', 'walletAddress', 'description?', 'specializations?', 'capabilities?', 'identityType?', 'chain?'],
      },
      updateAgentUri: {
        path: '/api/x402/actions/update-agent-uri',
        price: '$0.10 USDC',
        method: 'POST',
        description: "Tx-prepare for updating an agent's agentURI. Returns unsigned transaction; caller signs in wallet.",
        params: ['walletAddress', 'newAgentURI', 'chain?'],
      },
      fileVouch: {
        path: '/api/x402/actions/file-vouch',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for filing a vouch (with stake). Returns unsigned, payable transaction; caller signs in wallet.',
        params: ['walletAddress', 'targetAgent', 'stakeWei?', 'chain?'],
      },
      fileAttestation: {
        path: '/api/x402/actions/file-attestation',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for belief attestation (zk proof + public inputs). Returns unsigned transaction; caller signs in wallet.',
        params: ['walletAddress', 'proofBytes', 'publicInputs', 'chain?'],
      },
      createPartnershipBond: {
        path: '/api/x402/actions/create-partnership-bond',
        price: '$0.50 USDC',
        method: 'POST',
        description: 'Tx-prepare for creating an AI partnership bond on AIPartnershipBondsV2. Returns unsigned, payable transaction; caller signs in wallet.',
        params: ['walletAddress', 'partner', 'partnershipType?', 'stakeWei?', 'chain?'],
      },
      createAccountabilityBond: {
        path: '/api/x402/actions/create-accountability-bond',
        price: '$0.50 USDC',
        method: 'POST',
        description: 'Tx-prepare for creating an AI accountability bond on AIAccountabilityBondsV2. Returns unsigned, payable transaction; caller signs in wallet.',
        params: ['walletAddress', 'metricType?', 'durationSeconds?', 'stakeWei?', 'chain?'],
      },
      submitPartnershipMetrics: {
        path: '/api/x402/actions/submit-partnership-metrics',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for submitting hashed partnership metrics (humanGrowth, autonomy, dignity, tasksMastered, etc.). Privacy-preserving via salted hash.',
        params: ['walletAddress', 'bondId', 'metrics{...}', 'salt?', 'chain?'],
      },
      submitAccountabilityMetrics: {
        path: '/api/x402/actions/submit-accountability-metrics',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for submitting Flourishing Metrics (six dimensions of human flourishing) to AIAccountabilityBondsV2.submitMetrics().',
        params: ['walletAddress', 'bondId', 'metrics{6 dims}', 'chain?'],
      },
      requestBondDistribution: {
        path: '/api/x402/actions/request-bond-distribution',
        price: '$0.10 USDC',
        method: 'POST',
        description: 'Tx-prepare for requesting distribution payout on a Vaultfire bond (partnership or accountability).',
        params: ['walletAddress', 'bondId', 'bondType (partnership|accountability)', 'chain?'],
      },
      challengeBondMetrics: {
        path: '/api/x402/actions/challenge-bond-metrics',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for challenging submitted metrics on an AI Accountability Bond. Caller posts a challenge stake.',
        params: ['walletAddress', 'bondId', 'reason', 'stakeWei?', 'chain?'],
      },
      unvouch: {
        path: '/api/x402/actions/unvouch',
        price: '$0.10 USDC',
        method: 'POST',
        description: 'Tx-prepare for revoking a previously-filed vouch on VaultfireReputationStaking and unlocking stake.',
        params: ['walletAddress', 'targetAgent', 'chain?'],
      },
      submitFeedback: {
        path: '/api/x402/actions/submit-feedback',
        price: '$0.15 USDC',
        method: 'POST',
        description: 'Tx-prepare for submitting hashed feedback to ERC-8004 Reputation Registry. Privacy-preserving via salted hash.',
        params: ['walletAddress', 'targetAgent', 'feedback', 'salt?', 'chain?'],
      },
      requestValidation: {
        path: '/api/x402/actions/request-validation',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for opening a validation request on ERC-8004 Validation Registry — pay validators to verify a claim.',
        params: ['walletAddress', 'subject', 'claim', 'rewardWei?', 'chain?'],
      },
      submitValidation: {
        path: '/api/x402/actions/submit-validation',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for submitting a validation result on ERC-8004 Validation Registry as a staked validator.',
        params: ['walletAddress', 'requestId', 'verdict (bool)', 'evidence', 'chain?'],
      },
      stakeAsValidator: {
        path: '/api/x402/actions/stake-as-validator',
        price: '$0.20 USDC',
        method: 'POST',
        description: 'Tx-prepare for staking ETH on ERC-8004 Validation Registry to become a validator.',
        params: ['walletAddress', 'stakeWei?', 'chain?'],
      },
      deactivateAgent: {
        path: '/api/x402/actions/deactivate-agent',
        price: '$0.10 USDC',
        method: 'POST',
        description: 'Tx-prepare for deactivating an ERC-8004 agent registration. Reversible by re-registering.',
        params: ['walletAddress', 'chain?'],
      },
      grantConsent: {
        path: '/api/x402/actions/grant-consent',
        price: '$0.05 USDC',
        method: 'POST',
        description: 'Tx-prepare for granting consent for a specific purpose hash on ERC-8004 Identity Registry (KYA, opposite of KYC).',
        params: ['walletAddress', 'purposeHash (bytes32)', 'chain?'],
      },
      revokeConsent: {
        path: '/api/x402/actions/revoke-consent',
        price: '$0.05 USDC',
        method: 'POST',
        description: 'Tx-prepare for revoking previously-granted consent for a specific purpose hash on ERC-8004 Identity Registry.',
        params: ['walletAddress', 'purposeHash (bytes32)', 'chain?'],
      },
      reportMissionViolation: {
        path: '/api/x402/actions/report-mission-violation',
        price: '$0.15 USDC',
        method: 'POST',
        description: "Tx-prepare for reporting a mission violation against a module on Vaultfire MissionEnforcement. 'Morals over metrics' on-chain.",
        params: ['walletAddress', 'module', 'violationType', 'evidence', 'chain?'],
      },
      reportSurveillanceViolation: {
        path: '/api/x402/actions/report-surveillance-violation',
        price: '$0.15 USDC',
        method: 'POST',
        description: "Tx-prepare for reporting a surveillance violation against a module on Vaultfire AntiSurveillance. 'Privacy over surveillance' on-chain.",
        params: ['walletAddress', 'module', 'violationType', 'evidence', 'chain?'],
      },
      registerForPartnership: {
        path: '/api/x402/actions/register-for-partnership',
        price: '$0.30 USDC',
        method: 'POST',
        description: 'Tx-prepare for registering an agent for the Vaultfire partnership flow via the ERC-8004 Adapter. One-shot helper.',
        params: ['walletAddress', 'name', 'agentURI?', 'chain?'],
      },
      attestBelief: {
        path: '/api/x402/actions/attest-belief',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for attesting a post-quantum belief via Dilithium Attestor — CRYSTALS-Dilithium signature commitment.',
        params: ['walletAddress', 'beliefHash (bytes32)', 'signature', 'pubkey', 'chain?'],
      },

      // ----- Task Escrow lifecycle (6 priced) -----
      createTask: {
        path: '/api/x402/actions/create-task',
        price: '$0.30 USDC',
        method: 'POST',
        description: 'Tx-prepare for posting a task with USDC escrow on VaultfireTaskEscrow. 1% protocol fee, refunded on cancel.',
        params: ['walletAddress', 'description', 'rewardUSDC', 'deadline (unix sec)', 'chain?'],
      },
      acceptBid: {
        path: '/api/x402/actions/accept-bid',
        price: '$0.20 USDC',
        method: 'POST',
        description: 'Tx-prepare for accepting a bid on a Vaultfire task escrow. Assigns the task to the chosen bidding agent.',
        params: ['walletAddress', 'taskId', 'bidIndex', 'chain?'],
      },
      submitWork: {
        path: '/api/x402/actions/submit-work',
        price: '$0.20 USDC',
        method: 'POST',
        description: 'Tx-prepare for submitting completed work for a Vaultfire task escrow. Posts a deliverable URI on-chain.',
        params: ['walletAddress', 'taskId', 'deliverable (URI)', 'chain?'],
      },
      approveWork: {
        path: '/api/x402/actions/approve-work',
        price: '$0.20 USDC',
        method: 'POST',
        description: 'Tx-prepare for approving completed work — releases USDC from escrow to the assigned agent (minus protocol fee).',
        params: ['walletAddress', 'taskId', 'chain?'],
      },
      disputeTask: {
        path: '/api/x402/actions/dispute-task',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for opening a dispute on a Vaultfire task escrow. Freezes escrow pending governance resolution.',
        params: ['walletAddress', 'taskId', 'reason', 'chain?'],
      },
      cancelTask: {
        path: '/api/x402/actions/cancel-task',
        price: '$0.15 USDC',
        method: 'POST',
        description: 'Tx-prepare for cancelling a Vaultfire task escrow and triggering USDC refund per contract rules.',
        params: ['walletAddress', 'taskId', 'chain?'],
      },

      // ----- Street Cred (ERC-5192 soulbound badge, Base-only) -----
      streetCred: {
        path: '/api/x402/trust/street-cred',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Read any address\'s Vaultfire Street Cred profile via VaultfireStreetCred.computeScore() — soulbound badge tier, score 0-95, identity registration, active bonds, staked ETH.',
        params: ['address'],
      },
      mintStreetCred: {
        path: '/api/x402/actions/mint-street-cred',
        price: '$0.20 USDC',
        method: 'POST',
        description: 'Tx-prepare for minting your soulbound Vaultfire Street Cred badge (ERC-5192) on Base. One badge per address, non-transferable.',
        params: ['walletAddress', 'chain?'],
      },

      // ----- Tier 6: Session Keys / VKP / Delegation -----
      createSessionKey: {
        path: '/api/x402/actions/create-session-key',
        price: '$0.25 USDC',
        method: 'POST',
        description: 'Tx-prepare for creating an ERC-7702 session key with capability scoping, spend limit, expiry, and target whitelist.',
        params: ['walletAddress', 'sessionKey', 'expiry', 'spendLimit', 'capability', 'allowedTargets[]', 'chain?'],
      },
      revokeSessionKey: {
        path: '/api/x402/actions/revoke-session-key',
        price: '$0.10 USDC',
        method: 'POST',
        description: 'Tx-prepare for revoking an ERC-7702 session key by id. Immediate, on-chain.',
        params: ['walletAddress', 'sessionId', 'chain?'],
      },
      createVkpVault: {
        path: '/api/x402/actions/create-vkp-vault',
        price: '$0.40 USDC',
        method: 'POST',
        description: 'Tx-prepare for creating a Verifiable Knowledge Proof (VKP) vault — privacy-preserving data vault with retention window, privacy budget, and tiered access.',
        params: ['walletAddress', 'dataType', 'retentionPeriod', 'privacyBudget', 'accessTier', 'chain?'],
      },
      scopedDelegations: {
        path: '/api/x402/trust/scoped-delegations',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'List capability scope ids granted to an address from the ScopedDelegation registry.',
        params: ['address (required)', 'chain (default: base)'],
      },

      // ----- Tier 6: VNS commit-reveal (Base / Arbitrum / Polygon) -----
      commitVnsName: {
        path: '/api/x402/actions/commit-vns-name',
        price: '$0.10 USDC',
        method: 'POST',
        description: 'VNS commit-reveal step 1 — submit keccak256 commitment hash. Available on Base, Arbitrum, Polygon.',
        params: ['walletAddress', 'commitment (bytes32)', 'chain?'],
      },
      registerVnsName: {
        path: '/api/x402/actions/register-vns-name',
        price: '$0.30 USDC',
        method: 'POST',
        description: 'VNS commit-reveal step 2 — reveal name + secret. Mints VNS subdomain.',
        params: ['walletAddress', 'name', 'secret (bytes32)', 'chain?'],
      },
      transferVnsName: {
        path: '/api/x402/actions/transfer-vns-name',
        price: '$0.20 USDC',
        method: 'POST',
        description: 'Tx-prepare for transferring VNS ownership to another address.',
        params: ['walletAddress', 'newOwner', 'chain?'],
      },

      // ----- Tier 6: Bond Insurance Pool -----
      contributeInsurance: {
        path: '/api/x402/actions/contribute-insurance',
        price: '$0.20 USDC',
        method: 'POST',
        description: 'Tx-prepare for contributing ETH to the Bond Insurance Pool — community-owned slashed-bond reserve.',
        params: ['walletAddress', 'value (wei)', 'chain?'],
      },
      fileInsuranceClaim: {
        path: '/api/x402/actions/file-insurance-claim',
        price: '$0.30 USDC',
        method: 'POST',
        description: 'Tx-prepare for filing a claim against the Bond Insurance Pool. Supplies bond id, evidence URL, evidence hash.',
        params: ['walletAddress', 'bondId', 'evidenceUrl', 'evidenceHash (bytes32)', 'chain?'],
      },

      // ----- Tier 6: Capability Credentials -----
      issueCredential: {
        path: '/api/x402/actions/issue-credential',
        price: '$0.30 USDC',
        method: 'POST',
        description: 'Tx-prepare for issuing an ERC-8004 capability credential to an agent.',
        params: ['walletAddress', 'subject', 'capabilityType (bytes32)', 'expiry', 'chain?'],
      },
      revokeCredential: {
        path: '/api/x402/actions/revoke-credential',
        price: '$0.15 USDC',
        method: 'POST',
        description: 'Tx-prepare for revoking a previously-issued capability credential by id.',
        params: ['walletAddress', 'credentialId', 'chain?'],
      },

      // ----- Tier 6: Trust Oracle / Reputation -----
      submitTrustAttestation: {
        path: '/api/x402/actions/submit-trust-attestation',
        price: '$0.30 USDC',
        method: 'POST',
        description: 'Tx-prepare for submitting a typed trust attestation (score + confidence + evidence) to the Vaultfire Trust Oracle.',
        params: ['walletAddress', 'subject', 'score', 'confidence', 'evidenceHash (bytes32)', 'attestationType (bytes32)', 'chain?'],
      },
      slashReputation: {
        path: '/api/x402/actions/slash-reputation',
        price: '$0.30 USDC',
        method: 'POST',
        description: 'Tx-prepare for slashing a misbehaving agent\'s reputation stake (governance-gated on-chain).',
        params: ['walletAddress', 'agent', 'chain?'],
      },
      triggerReputationDecay: {
        path: '/api/x402/actions/trigger-reputation-decay',
        price: '$0.10 USDC',
        method: 'POST',
        description: 'Tx-prepare for triggering time-based reputation decay for an agent — anyone can call.',
        params: ['walletAddress', 'agent', 'chain?'],
      },
      reputationDecay: {
        path: '/api/x402/trust/reputation-decay',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Read freshness-adjusted reputation — decayed score, base score, days since activity, total activities.',
        params: ['address (required)', 'chain (default: base)'],
      },

      // ----- Tier 6: Onboarding & Bridge -----
      batchOnboard: {
        path: '/api/x402/actions/batch-onboard',
        price: '$0.50 USDC',
        method: 'POST',
        description: 'One-shot atomic agent onboarding on Base — registers identity, sets URI, posts initial bond. Base only.',
        params: ['walletAddress', 'name', 'uri', 'commitment (bytes32)', 'partner', 'metricKey', 'chain?'],
      },
      bridgeTrustMessage: {
        path: '/api/x402/actions/bridge-trust-message',
        price: '$0.40 USDC',
        method: 'POST',
        description: 'Tx-prepare for sending a cross-chain reputation message — propagates score across chains.',
        params: ['walletAddress', 'destinationAgent', 'destinationChainId', 'score', 'totalBonds', 'totalAttestations', 'chain?'],
      },

      // ----- Tier 6: Safety / SLA / Governance reads -----
      safetyStatus: {
        path: '/api/x402/trust/safety-status',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Read an agent\'s current safety status from AgentSafetyManager — status enum (Active/Paused/Suspended/Banned), last change, who, why.',
        params: ['address (required)', 'chain (default: base)'],
      },
      slaStatus: {
        path: '/api/x402/trust/sla-status',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Read an agent\'s SLA performance — active SLAs, total stake, total penalized, violation count from AgentSLAEnforcer.',
        params: ['address (required)', 'chain (default: base)'],
      },
      flourishingMetrics: {
        path: '/api/x402/trust/flourishing-metrics',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Read latest FlourishingMetricsOracle round for a metric key — value + roundId.',
        params: ['metricKey (bytes32, required)', 'chain (default: base)'],
      },
      governanceProposals: {
        path: '/api/x402/trust/governance-proposals',
        price: '$0.02 USDC',
        method: 'GET',
        description: 'Read a MultisigGovernance transaction by id — target, value, calldata, executed, confirmations, expiry.',
        params: ['txId (required)', 'chain (default: base)'],
      },

      // ----- Chainlink Oracle (Tier 1 Chainlink integration) -----
      oraclePriceFeed: {
        path: '/api/x402/oracle/price-feed',
        price: '$0.01 USDC',
        method: 'GET',
        description:
          'Read any supported Chainlink Data Feed (ETH/USD, BTC/USD, LINK/USD, USDC/USD, AVAX/USD, MATIC/USD) on Base, Avalanche, Arbitrum, or Polygon. Returns answer, decimals, roundId, updatedAt, and freshness. Data source: Chainlink decentralized oracle network.',
        params: ['pair (required: eth-usd|btc-usd|usdc-usd|link-usd|avax-usd|matic-usd)', 'chain (default: base)'],
      },
      oracleAgentStakeUsd: {
        path: '/api/x402/oracle/agent-stake-usd',
        price: '$0.02 USDC',
        method: 'GET',
        description:
          "Compose Vaultfire's on-chain bond data with Chainlink's price feed to return USD-denominated agent stake. Uniquely enabled by the Chainlink integration — Vaultfire owns the agent-truth side, Chainlink owns the market-data side.",
        params: ['address (required)', 'chain (default: base)'],
      },
      oracleChainlinkStatus: {
        path: '/api/x402/oracle/chainlink-status',
        price: 'free',
        method: 'GET',
        description:
          'Free Chainlink oracle discovery beacon. Lists all 15 supported (chain, pair) feeds with live freshness, attribution to Chainlink, and links to the priced oracle endpoints.',
      },

      // ----- Free -----
      health: {
        path: '/api/x402/trust/health',
        price: 'free',
        method: 'GET',
        description: 'This endpoint. Discovery beacon for crawlers and agents.',
      },
    },

    // ===== Live snapshot (so crawlers can verify it's a real, active service) =====
    live: {
      totalIdentities: hubStats?.totalIdentities ?? null,
      activeBonds: hubStats?.activeBonds ?? null,
      contractsDeployed: 134,
      chainBreakdown: { base: 36, avalanche: 32, arbitrum: 33, polygon: 33 },
    },

    // ===== Provider =====
    provider: {
      name: 'Vaultfire Protocol',
      url: 'https://theloopbreaker.com',
      mission:
        'morals over metrics, privacy over surveillance, freedom over control, humanity over everything',
    },

    hub: hubHealth,
  }, {
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Cache-Control': 'public, max-age=60',
    },
  });
}
