/**
 * GET /api/x402/bonds/agent-bond-status?address=0x...
 *
 * x402 payment-gated agent bond status — $0.01 USDC per query.
 * Payments routed through CDP facilitator for Bazaar discovery.
 *
 * Look up any AI agent's bond posture — active accountability bonds,
 * active partnership bonds, total staked ETH, and reputation context.
 * The agent-level companion to /api/x402/bonds/overview.
 *
 * Proxies to the existing hub /api/agent/partnerships endpoint, then
 * augments with a bond-economy summary block.
 */

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, submit on-chain Flourishing Metrics, and earn distribution when they deliver. ' +
  'Morals over metrics, on-chain.';

const handler = async (req: NextRequest) => {
  const { searchParams } = req.nextUrl;
  const address = searchParams.get('address');
  const chain = searchParams.get('chain') || 'base';

  if (!address) {
    return NextResponse.json(
      { error: 'address query parameter is required' },
      { status: 400 }
    );
  }

  try {
    const params = new URLSearchParams();
    params.set('address', address);
    const hubUrl = `${req.nextUrl.origin}/api/agent/partnerships?${params.toString()}`;
    const hubRes = await fetch(hubUrl);
    const data = await hubRes.json();

    return NextResponse.json(
      {
        service: 'vaultfire-bonds',
        headline: HEADLINE,
        address,
        chain,
        bondSummary: {
          activeCount: data?.count ?? data?.bonds?.length ?? null,
          bonds: data?.bonds ?? [],
        },
        flourishingFramework: 'Bonds reward flourishing — agents that deliver on the six Flourishing Metrics dimensions earn distribution.',
        nextSteps: {
          createAccountabilityBond: '/api/x402/actions/create-accountability-bond',
          createPartnershipBond: '/api/x402/actions/create-partnership-bond',
          submitMetrics: '/api/x402/actions/submit-accountability-metrics',
        },
        _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 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: look up any agent\'s bond posture ' +
    '(active accountability + partnership bonds, total staked, partner addresses). Reads ERC-8004 + ' +
    'AIAccountabilityBondsV2 + AIPartnershipBondsV2 live on-chain.',
  mimeType: 'application/json',
  outputSchema: {
    type: 'object',
    properties: {
      service: { type: 'string' },
      headline: { type: 'string', description: 'Vaultfire bond-economy pitch' },
      address: { type: 'string', description: 'Agent wallet address queried' },
      chain: { type: 'string', description: 'Chain context (default: base)' },
      bondSummary: {
        type: 'object',
        description: 'Active bond count + bond detail list',
        properties: {
          activeCount: { type: 'number', description: 'Number of active bonds for this agent' },
          bonds: { type: 'array', description: 'Bond detail objects' },
        },
      },
      flourishingFramework: { type: 'string', description: 'How Vaultfire bonds reward flourishing' },
      nextSteps: {
        type: 'object',
        description: 'Bond-action endpoints to create or submit metrics',
      },
    },
  },
}) as (req: NextRequest) => Promise<Response>;
