/**
 * GET /api/agent/attestation?address=0x...&chain=base  — Check belief attestation status
 *
 * Three attestation contracts:
 *   - BeliefAttestationVerifier: Verifies AI belief systems and value alignment
 *   - ProductionBeliefAttestationVerifier: Production-grade belief verification
 *   - DilithiumAttestor: Post-quantum (CRYSTALS-Dilithium) attestation signatures
 *
 * Belief-weighted governance — first in the industry (not token-weighted).
 *
 * SECURITY: Read-only. No private keys accepted.
 */

import { NextRequest, NextResponse } from 'next/server';
import { resolveChain, SUPPORTED_CHAINS } from '../../_lib/resolve-chain';
import { BELIEF_ATTESTATION, PRODUCTION_BELIEF, DILITHIUM_ATTESTOR, 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 });
  }

  return NextResponse.json({
    chain,
    chainId: CHAIN_IDS[chain],
    contracts: {
      beliefAttestationVerifier: BELIEF_ATTESTATION[chain],
      productionBeliefVerifier: PRODUCTION_BELIEF[chain],
      dilithiumAttestor: DILITHIUM_ATTESTOR[chain],
    },
    explorer: {
      beliefAttestationVerifier: `${EXPLORER_URLS[chain]}/address/${BELIEF_ATTESTATION[chain]}`,
      productionBeliefVerifier: `${EXPLORER_URLS[chain]}/address/${PRODUCTION_BELIEF[chain]}`,
      dilithiumAttestor: `${EXPLORER_URLS[chain]}/address/${DILITHIUM_ATTESTOR[chain]}`,
    },
    query: address || null,
    abi: {
      beliefAttestation: {
        verifyBelief: 'verifyBelief(address agent, bytes32 beliefHash) → bool',
        submitBelief: 'submitBelief(bytes32 beliefHash, bytes signature)',
        getBeliefWeight: 'getBeliefWeight(address agent) → uint256',
      },
      dilithium: {
        verifyPostQuantum: 'verifyDilithium(bytes32 message, bytes signature, bytes publicKey) → bool',
        attestWithDilithium: 'attest(address agent, bytes32 dataHash, bytes dilithiumSig)',
      },
    },
    description: 'Belief-weighted governance (not token-weighted). Includes post-quantum Dilithium attestation.',
  }, { headers: CORS });
}
