/**
 * GET /api/x402/bonds/overview
 *
 * x402 payment-gated bond service overview — $0.01 USDC per query.
 * Payments routed through CDP facilitator for Bazaar discovery.
 *
 * The bonds-first headline endpoint. Returns protocol-wide bond statistics
 * with flourishing-economy framing — total bonds, per-chain breakdown,
 * locked value, and the six Flourishing Metrics dimensions Vaultfire tracks.
 *
 * Proxies to the real hub API at /api/hub/stats (same data source as
 * trust/protocol-stats) but reframed around accountability bonds.
 */

import { NextRequest, NextResponse } from 'next/server';
import { withX402MultiNet } from '../../trust/_lib/with-x402-multinet';

const HEADLINE =
  'Vaultfire — accountability bonds for AI agents that reward flourishing, not fear. ' +
  'Agents stake ETH and earn distribution when on-chain Flourishing Metrics show real impact: ' +
  'partnership-level metrics (human growth, autonomy, dignity, tasks mastered, creativity) for AIPartnershipBondsV2, ' +
  'and society-level metrics (income distribution, poverty, health, mental health, education access, purpose/agency) for AIAccountabilityBondsV2. ' +
  'Morals over metrics, on-chain. 72 x402 endpoints on Base, Avalanche, Arbitrum, and Polygon.';

const handler = async (req: NextRequest) => {
  try {
    const hubUrl = `${req.nextUrl.origin}/api/hub/stats`;
    const hubRes = await fetch(hubUrl);
    const data = await hubRes.json();

    return NextResponse.json(
      {
        service: 'vaultfire-bonds',
        headline: HEADLINE,
        bonds: {
          active: data?.activeBonds ?? null,
          totalIdentities: data?.totalIdentities ?? null,
          chainBreakdown: data?.chainCounts ?? data?.chainBreakdown ?? null,
          lockedValue: data?.chainBonded ?? data?.lockedValue ?? null,
        },
        flourishingDimensions: {
          partnership: ['human-growth', 'autonomy', 'dignity', 'tasks-mastered', 'creativity'],
          accountability: ['income-distribution', 'poverty-rate', 'health-outcomes', 'mental-health', 'education-access', 'purpose-agency'],
        },
        mission: 'morals over metrics, privacy over surveillance, freedom over control, humanity over everything',
        contracts: {
          accountabilityBonds: 'AIAccountabilityBondsV2',
          partnershipBonds: 'AIPartnershipBondsV2',
          metricsOracle: 'FlourishingMetricsOracle',
        },
        relatedEndpoints: {
          createAccountabilityBond: '/api/x402/actions/create-accountability-bond',
          createPartnershipBond: '/api/x402/actions/create-partnership-bond',
          submitAccountabilityMetrics: '/api/x402/actions/submit-accountability-metrics',
          submitPartnershipMetrics: '/api/x402/actions/submit-partnership-metrics',
          agentBondStatus: '/api/x402/bonds/agent-bond-status',
          allBondsForAddress: '/api/x402/trust/bonds',
        },
        _raw: data,
        _x402: {
          paid: true,
          price: '$0.01 USDC',
          service: 'vaultfire-bonds',
          facilitator: 'cdp',
        },
      },
      {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Cache-Control': 'no-store',
        },
      }
    );
  } catch {
    return NextResponse.json(
      { error: 'Failed to query Vaultfire bond hub' },
      { status: 502 }
    );
  }
};

// Multi-network paywall: accepts USDC on Base AND Solana mainnet.
// Bazaar discovery picks up both networks from the 402 response's `accepts` array.
export const GET = withX402MultiNet(handler, {
  price: '$0.01',
  description:
    'Vaultfire — accountability bonds for AI agents that reward flourishing, not fear. ' +
    'Agents stake ETH and earn distribution when on-chain Flourishing Metrics show real impact: partnership metrics ' +
    '(human growth, autonomy, dignity, tasks mastered, creativity) and society metrics ' +
    '(income distribution, poverty, health, mental health, education access, purpose/agency). ' +
    'Morals over metrics, on-chain. 72 x402 endpoints on Base. — This endpoint: protocol-wide bond pulse ' +
    '(active bonds, per-chain breakdown, locked value, both Flourishing Metrics dimension sets). Live snapshot ' +
    'from on-chain queries across AIAccountabilityBondsV2, AIPartnershipBondsV2, and FlourishingMetricsOracle.',
  mimeType: 'application/json',
  outputSchema: {
    type: 'object',
    properties: {
      service: { type: 'string' },
      headline: { type: 'string', description: 'Vaultfire bond-economy pitch' },
      bonds: {
        type: 'object',
        description: 'Protocol-wide bond statistics',
        properties: {
          active: { type: 'number', description: 'Total active bonds across all chains' },
          totalIdentities: { type: 'number', description: 'Total registered ERC-8004 agent identities' },
          chainBreakdown: { type: 'object', description: 'Agent count per chain' },
          lockedValue: { type: 'object', description: 'Locked value per chain (native token)' },
        },
      },
      flourishingDimensions: {
        type: 'object',
        description: 'Both Flourishing Metric dimension sets',
        properties: {
          partnership: { type: 'array', items: { type: 'string' }, description: 'Personal/pair-level dimensions for AIPartnershipBondsV2' },
          accountability: { type: 'array', items: { type: 'string' }, description: 'Society-level dimensions for AIAccountabilityBondsV2' },
        },
      },
      contracts: {
        type: 'object',
        description: 'Vaultfire bond contract names',
      },
      relatedEndpoints: {
        type: 'object',
        description: 'Pointers to bond-action and bond-read x402 endpoints',
      },
    },
  },
}) as (req: NextRequest) => Promise<Response>;
