/**
 * GET /api/agent/flourishing?address=0x...&chain=base  — Read flourishing metrics
 *
 * FlourishingMetricsOracle — Measures positive human outcomes.
 * Tracks whether AI agent interactions lead to human flourishing,
 * not just task completion.
 *
 * SECURITY: Read-only. No private keys accepted.
 */

import { NextRequest, NextResponse } from 'next/server';
import { resolveChain, SUPPORTED_CHAINS } from '../../_lib/resolve-chain';
import { FLOURISHING_ORACLE, CHAIN_IDS, EXPLORER_URLS, type SupportedChain } from '../../../lib/contracts';
import { checkRateLimit, RATE_LIMIT_GET } from '../../../lib/rate-limit';

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

export async function GET(request: NextRequest) {
  const rl = checkRateLimit(request, RATE_LIMIT_GET);
  if (rl) return rl;

  const params = request.nextUrl.searchParams;
  const chain = resolveChain(params.get('chain')) as SupportedChain;
  const address = params.get('address');

  if (!chain || !SUPPORTED_CHAINS.includes(chain)) {
    return NextResponse.json({ error: `Invalid chain. Use: ${SUPPORTED_CHAINS.join(', ')}` }, { status: 400, headers: CORS });
  }

  const contract = FLOURISHING_ORACLE[chain];
  return NextResponse.json({
    chain,
    chainId: CHAIN_IDS[chain],
    contract,
    explorerUrl: `${EXPLORER_URLS[chain]}/address/${contract}`,
    query: address || null,
    abi: {
      getFlourishingScore: 'getFlourishingScore(address agent) → uint256',
      reportOutcome: 'reportOutcome(address agent, uint256 score, bytes32 evidenceHash)',
      getAverageScore: 'getAverageScore() → uint256',
    },
    description: 'Measures whether AI agent interactions lead to positive human outcomes — not just task completion.',
  }, { headers: CORS });
}
