import { NextRequest, NextResponse } from 'next/server';
import { ethers } from 'ethers';
import { resolveChain, SUPPORTED_CHAINS } from '../../_lib/resolve-chain';
import { withFailover } from '../../_lib/rpc-retry';

/**
 * GET /api/agent/performance
 *
 * Query performance metrics by agent address from the VaultfireTrustOracle contract.
 *
 * Query params:
 *   ?address=0x...    — (required) agent address to look up
 *   ?chain=base       — chain to query (default: "base")
 *
 * Returns:
 *   totalAttestations, averageQuality, verifiedAttestations, taskCompletions, lastUpdated
 */

const CONTRACTS: Record<string, string> = {
  base:      '0xF945aA87dB4E1d14aa7d0572501afa166374B776',
  avalanche: '0x01C479F0c039fEC40c0Cf1c5C921bab457d57441',
  arbitrum:  '0xFeF83A66fC1f3c8311070FDd502cd90deD0B3C33',
  polygon:   '0xFa8ed66E27379942cB90BB5f612F0170a5dE4924',
};

const ABI = [
  {
    name: 'getPerformance',
    type: 'function',
    stateMutability: 'view',
    inputs: [{ name: 'agent', type: 'address' }],
    outputs: [
      { name: 'totalAttestations',    type: 'uint256' },
      { name: 'averageQuality',       type: 'uint256' },
      { name: 'verifiedAttestations', type: 'uint256' },
      { name: 'taskCompletions',      type: 'uint256' },
      { name: 'lastUpdated',          type: 'uint256' },
    ],
  },
];

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const chain = resolveChain(searchParams.get('chain'));
    const address = searchParams.get('address');

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

    if (!ethers.isAddress(address)) {
      return NextResponse.json({ error: 'Invalid wallet address' }, { status: 400 });
    }

    if (!chain) {
      return NextResponse.json(
        { error: `Unsupported chain. Use one of: ${SUPPORTED_CHAINS.join(', ')} (or chain IDs: 8453, 43114, 42161, 137)` },
        { status: 400 },
      );
    }
    const contractAddress = CONTRACTS[chain];

    const perf = await withFailover(chain, async (provider) => {
      const contract = new ethers.Contract(contractAddress, ABI, provider);
      return contract.getPerformance(address);
    });

    return NextResponse.json({
      address,
      chain,
      contract: contractAddress,
      performance: {
        totalAttestations:    perf.totalAttestations.toString(),
        averageQuality:       perf.averageQuality.toString(),
        verifiedAttestations: perf.verifiedAttestations.toString(),
        taskCompletions:      perf.taskCompletions.toString(),
        lastUpdated:          perf.lastUpdated.toString(),
      },
    });
  } catch (error: any) {
    // VF-014: Log detailed error server-side; return generic message to client
    console.error('[agent/performance] Error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
