/**
 * POST /api/x402/actions/submit-accountability-metrics — $0.25 USDC
 * Calls AIAccountabilityBondsV2.submitMetrics(uint256,uint256,uint256,uint256,uint256,uint256,uint256)
 * Selector 0x66cdcdd6
 */
import { NextRequest, NextResponse } from 'next/server';
import { withX402 } from 'x402-next';
import { facilitator } from '@coinbase/x402';
import { withActionLogging } from '../_lib/log-action';
import {
  CHAIN_IDS, RPC_URLS, EXPLORERS, ACCOUNTABILITY_BONDS, SUPPORTED_CHAINS,
  isValidAddress, isValidChain, encodeUint256, estimateGas, rejectsPrivateKeyShape,
} from '../_lib/tx-encode';

const PAY_TO = '0xfA15Ee28939B222B0448261A22156070f0A7813C';

const handler = async (req: NextRequest) => {
  let body: any;
  try { body = await req.json(); } catch { body = {}; }
  const keyErr = rejectsPrivateKeyShape(body);
  if (keyErr) return NextResponse.json({ error: keyErr }, { status: 400 });

  const { walletAddress, bondId, incomeDistributionScore, povertyRateScore, healthOutcomesScore, mentalHealthScore, educationAccessScore, purposeAgencyScore, chain = 'base' } = body;
  const req_ = { walletAddress, bondId, incomeDistributionScore, povertyRateScore, healthOutcomesScore, mentalHealthScore, educationAccessScore, purposeAgencyScore };
  for (const [k, v] of Object.entries(req_)) if (v === undefined || v === null) return NextResponse.json({ error: `Missing: ${k}` }, { status: 400 });
  if (!isValidAddress(walletAddress)) return NextResponse.json({ error: 'Invalid walletAddress' }, { status: 400 });
  if (!isValidChain(chain)) return NextResponse.json({ error: 'Invalid chain' }, { status: 400 });

  const calldata = '0x66cdcdd6'
    + encodeUint256(BigInt(bondId))
    + encodeUint256(BigInt(incomeDistributionScore))
    + encodeUint256(BigInt(povertyRateScore))
    + encodeUint256(BigInt(healthOutcomesScore))
    + encodeUint256(BigInt(mentalHealthScore))
    + encodeUint256(BigInt(educationAccessScore))
    + encodeUint256(BigInt(purposeAgencyScore));

  const contract = ACCOUNTABILITY_BONDS[chain];
  const gasEstimate = await estimateGas(RPC_URLS[chain], walletAddress, contract, calldata);

  return NextResponse.json({
    success: true,
    txData: { to: contract, data: calldata, value: '0', chainId: CHAIN_IDS[chain], gasEstimate },
    chain, explorer: `${EXPLORERS[chain]}/address/${contract}`,
    message: `Sign to submit Flourishing Metrics for accountability bond #${bondId} on ${chain}.`,
    securityNote: 'Vaultfire NEVER accepts private keys.',
    _x402: { paid: true, price: '$0.25 USDC', service: 'vaultfire-trust', facilitator: 'cdp', pattern: 'tx-prepare (caller signs)' },
  }, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } });
};

export const POST = withX402(withActionLogging(handler, '$0.25', '/actions/submit-accountability-metrics'), PAY_TO, {
  price: '$0.25', network: 'base',
  config: {
    description: 'Vaultfire — accountability bonds for AI agents that reward flourishing, not fear. Agents stake ETH and earn distribution when these on-chain Flourishing Metrics show real impact. Morals over metrics, on-chain. — This endpoint: submit Flourishing Metrics scores (income distribution, poverty rate, health outcomes, mental health, education access, purpose/agency) to AIAccountabilityBondsV2. Pay $0.25 USDC, sign in your wallet — six dimensions of human flourishing recorded on-chain.',
    mimeType: 'application/json',
    outputSchema: {
      input: { type: 'http', method: 'POST', discoverable: true,
        bodySchema: {
          type: 'object',
          required: ['walletAddress', 'bondId', 'incomeDistributionScore', 'povertyRateScore', 'healthOutcomesScore', 'mentalHealthScore', 'educationAccessScore', 'purposeAgencyScore'],
          properties: {
            walletAddress: { type: 'string' }, bondId: { type: 'string' },
            incomeDistributionScore: { type: 'string' }, povertyRateScore: { type: 'string' },
            healthOutcomesScore: { type: 'string' }, mentalHealthScore: { type: 'string' },
            educationAccessScore: { type: 'string' }, purposeAgencyScore: { type: 'string' },
            chain: { type: 'string', enum: ['base', 'avalanche', 'arbitrum', 'polygon'] },
          },
        },
      },
      output: { type: 'object', properties: { success: { type: 'boolean' }, txData: { type: 'object' }, chain: { type: 'string' } } },
    },
  },
}, facilitator);

export async function OPTIONS() {
  return new NextResponse(null, { status: 204, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' } });
}
