import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { BGP_COMMUNITY_DB, decodeCommunities } from './bgp-community-db.js';

interface CommunityQuery {
  asn?: string;
}

export async function bgpCommunitiesRoutes(fastify: FastifyInstance): Promise<void> {
  fastify.get<{ Querystring: CommunityQuery }>(
    '/communities',
    async (request: FastifyRequest<{ Querystring: CommunityQuery }>, reply: FastifyReply) => {
      let asnStr = request.query.asn || '';
      const asn = asnStr.replace(/[^0-9]/g, '');
      
      if (!asn) {
        return reply.status(400).send({ error: 'asn required' });
      }

      try {
        const url = `https://stat.ripe.net/data/bgp-state/data.json?resource=AS${asn}`;
        
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 6000);
        
        const response = await fetch(url, { signal: controller.signal });
        clearTimeout(timeoutId);
        
        if (!response.ok) {
           throw new Error(`RIPE Stat API returned ${response.status}`);
        }
        
        const data = await response.json();
        
        const rawComms: string[] = [];
        if (data && data.data && data.data.bgp_state) {
          for (const entry of data.data.bgp_state.slice(0, 50)) {
            if (entry.community) {
                rawComms.push(...entry.community);
            }
          }
        }
        
        const unique = [...new Set(rawComms.map((c: any) => Array.isArray(c) ? c.join(':') : String(c)))];
        const decoded = unique.map(k => ({ raw: k, known: BGP_COMMUNITY_DB[k] || null }));
        
        // Cache control
        reply.header('Cache-Control', 'public, max-age=3600');
        reply.header('Access-Control-Allow-Origin', '*');
        
        return reply.send({
          asn: `AS${asn}`,
          communities: decoded,
          db_size: Object.keys(BGP_COMMUNITY_DB).length
        });
      } catch (error: any) {
        reply.header('Access-Control-Allow-Origin', '*');
        return reply.status(200).send({
          asn: `AS${asn}`,
          communities: [],
          error: error.message
        });
      }
    }
  );
}
