/**
 * GET /api/agent/privacy?address=0x...&chain=base  — Check privacy + anti-surveillance status
 *
 * AntiSurveillance + PrivacyGuarantees — Two contracts that protect agent interactions.
 * AntiSurveillance prevents unauthorized monitoring.
 * PrivacyGuarantees provides cryptographic privacy protections.
 *
 * SECURITY: Read-only. No private keys accepted.
 */

import { NextRequest, NextResponse } from 'next/server';
import { resolveChain, SUPPORTED_CHAINS } from '../../_lib/resolve-chain';
import { ANTI_SURVEILLANCE, PRIVACY_GUARANTEES, CHAIN_IDS, RPC_URLS, 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: {
      antiSurveillance: ANTI_SURVEILLANCE[chain],
      privacyGuarantees: PRIVACY_GUARANTEES[chain],
    },
    explorer: {
      antiSurveillance: `${EXPLORER_URLS[chain]}/address/${ANTI_SURVEILLANCE[chain]}`,
      privacyGuarantees: `${EXPLORER_URLS[chain]}/address/${PRIVACY_GUARANTEES[chain]}`,
    },
    query: address || null,
    abi: {
      antiSurveillance: {
        grantConsent: 'grantConsent(bytes32 consentHash)',
        revokeConsent: 'revokeConsent(bytes32 consentHash)',
        hasConsent: 'hasConsent(address agent, bytes32 consentHash) → bool',
      },
      privacyGuarantees: {
        getPrivacyLevel: 'getPrivacyLevel(address agent) → uint8',
        setPrivacyLevel: 'setPrivacyLevel(uint8 level)',
        isPrivacyCompliant: 'isPrivacyCompliant(address agent) → bool',
      },
    },
    description: 'Privacy protections and anti-surveillance guarantees for AI agent interactions.',
  }, { headers: CORS });
}
