/**
 * GET /api/x402/trust/safety-status?address=0x...&chain=base — $0.02 USDC
 * Calls AgentSafetyManager.getAgentStatus(address)
 * Selector 0xdc10a652 (verified vs viem.toFunctionSelector + on-chain dispatcher;
 * full ABI 100% matched repo abi vs on-chain bytecode).
 *
 * Returns: status (enum 0=Active, 1=Frozen, 2=SafeMode, 3=Terminated),
 * statusChangedAt (unix), changedBy (address), reason (string).
 */
import { NextRequest, NextResponse } from 'next/server';
import { withX402MultiNet } from '../_lib/with-x402-multinet';
import { ethers } from 'ethers';
import { withFailover } from '../../../_lib/rpc-retry';

const ADDRS: Record<string, { address: string; rpc: string; chainId: number; explorer: string }> = {
  base:      { address: '0x6B580f08ecA90778AC41FA1290557c86DeEfB1F5', rpc: 'https://base-rpc.publicnode.com', chainId: 8453, explorer: 'https://basescan.org' },
  avalanche: { address: '0xC46d9d20727060E563392A1F4DB00a3877807cb7', rpc: 'https://api.avax.network/ext/bc/C/rpc', chainId: 43114, explorer: 'https://snowtrace.io' },
  arbitrum:  { address: '0xa2bE41F6fA82dE27fbB7838A0308d05741C1e9c8', rpc: 'https://arb1.arbitrum.io/rpc', chainId: 42161, explorer: 'https://arbiscan.io' },
  polygon:   { address: '0xCA5380aF3dd6a29C217cE0c0c9f45999B47cbdF3', rpc: 'https://polygon-bor-rpc.publicnode.com', chainId: 137, explorer: 'https://polygonscan.com' },
};

const ABI = [
  'function getAgentStatus(address agent) view returns (uint8 status, uint256 statusChangedAt, address changedBy, string reason)',
] as const;

const STATUS_NAMES: Record<number, string> = { 0: 'Active', 1: 'Frozen', 2: 'SafeMode', 3: 'Terminated' };

const handler = async (req: NextRequest) => {
  const { searchParams } = req.nextUrl;
  const address = searchParams.get('address');
  const chain = (searchParams.get('chain') || 'base').toLowerCase();
  if (!address) return NextResponse.json({ error: 'address query parameter is required' }, { status: 400 });
  if (!ethers.isAddress(address)) return NextResponse.json({ error: 'Invalid address' }, { status: 400 });
  const cfg = ADDRS[chain];
  if (!cfg) return NextResponse.json({ error: 'Invalid chain. Use base|avalanche|arbitrum|polygon' }, { status: 400 });

  try {
    const result = await withFailover(chain, async (provider) => {
      const c = new ethers.Contract(cfg.address, ABI, provider);
      return await c.getAgentStatus(address);
    });
    const statusNum = Number(result[0]);
    return NextResponse.json({
      address: address.toLowerCase(),
      chain,
      contractAddress: cfg.address,
      status: statusNum,
      statusName: STATUS_NAMES[statusNum] ?? 'Unknown',
      statusChangedAt: Number(result[1]),
      changedBy: String(result[2]).toLowerCase(),
      reason: String(result[3] || ''),
      explorerUrl: `${cfg.explorer}/address/${cfg.address}`,
      _x402: { paid: true, price: '$0.02 USDC', service: 'vaultfire-trust', facilitator: 'cdp' },
    }, { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } });
  } catch (e: any) {
    return NextResponse.json({ error: 'Failed to query AgentSafetyManager', detail: e?.shortMessage || e?.message || String(e) }, { 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.02',
  description: 'Look up an agent\'s on-chain safety status via AgentSafetyManager.getAgentStatus() — status enum (Active/Frozen/SafeMode/Terminated), when it last changed, who changed it, and the human-readable reason.',
    mimeType: 'application/json',
    outputSchema: {
      type: 'object',
      properties: {
        address: { type: 'string' },
        chain: { type: 'string' },
        contractAddress: { type: 'string' },
        status: { type: 'number', description: '0=Active, 1=Frozen, 2=SafeMode, 3=Terminated' },
        statusName: { type: 'string' },
        statusChangedAt: { type: 'number' },
        changedBy: { type: 'string' },
        reason: { type: 'string' },
        explorerUrl: { type: 'string' },
      },
    }
}) as (req: NextRequest) => Promise<Response>;
