/**
 * GET /api/agent/governance?chain=base  — Read governance status and proposals
 *
 * MultisigGovernance — Multi-signature governance for protocol changes.
 * Ensures no single entity can unilaterally modify the protocol.
 *
 * SECURITY: Read-only. No private keys accepted.
 */

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

const PROPOSAL_COUNT_SEL = '0xda35c664'; // proposalCount()

async function rpcCall(rpc: string, to: string, data: string): Promise<string> {
  const res = await fetch(rpc, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_call', params: [{ to, data }, 'latest'] }) });
  const json = await res.json();
  return json.result || '0x0';
}

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

  const chain = resolveChain(request.nextUrl.searchParams.get('chain')) as SupportedChain;
  if (!chain || !SUPPORTED_CHAINS.includes(chain)) {
    return NextResponse.json({ error: `Invalid chain. Use: ${SUPPORTED_CHAINS.join(', ')}` }, { status: 400, headers: CORS });
  }

  const contract = MULTISIG_GOVERNANCE[chain];
  const rpc = RPC_URLS[chain];

  try {
    const rawCount = await rpcCall(rpc, contract, PROPOSAL_COUNT_SEL);
    return NextResponse.json({
      chain,
      chainId: CHAIN_IDS[chain],
      contract,
      totalProposals: parseInt(rawCount, 16) || 0,
      explorerUrl: `${EXPLORER_URLS[chain]}/address/${contract}`,
      abi: {
        proposalCount: 'proposalCount() → uint256',
        getProposal: 'getProposal(uint256 id) → (address proposer, bytes data, bool executed, uint256 confirmations)',
        submitProposal: 'submitProposal(bytes data)',
        confirmProposal: 'confirmProposal(uint256 id)',
        executeProposal: 'executeProposal(uint256 id)',
      },
      description: 'Multi-signature governance. No single entity can unilaterally modify the protocol.',
    }, { headers: CORS });
  } catch {
    return NextResponse.json({ error: 'Failed to read governance data' }, { status: 502, headers: CORS });
  }
}
