/**
 * GET /api/agent/mission?address=0x...&chain=base  — Check mission compliance for an agent
 *
 * MissionEnforcement — Ensures AI agents follow their stated mission.
 * The contract records mission hashes and allows verification of alignment.
 *
 * SECURITY: Read-only. No private keys accepted.
 */

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

  const contract = MISSION_ENFORCEMENT[chain];
  return NextResponse.json({
    chain,
    chainId: CHAIN_IDS[chain],
    contract,
    explorerUrl: `${EXPLORER_URLS[chain]}/address/${contract}`,
    query: address || null,
    abi: {
      getMission: 'getMission(address agent) → bytes32 missionHash',
      setMission: 'setMission(bytes32 missionHash)',
      verifyMission: 'verifyMission(address agent, bytes32 missionHash) → bool',
      isMissionCompliant: 'isMissionCompliant(address agent) → bool',
    },
    description: 'Enforces AI agent mission alignment. Agents register their mission hash on-chain.',
  }, { headers: CORS });
}
