import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';

interface LookingGlassQuery {
  prefix?: string;
  asn?: string;
}

async function fetchWithRetry(url: string, retries = 1, timeout = 10000): Promise<any> {
  for (let i = 0; i <= retries; i++) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    try {
      const response = await fetch(url, { signal: controller.signal });
      clearTimeout(timeoutId);
      if (!response.ok) {
        if (i === retries) throw new Error(`HTTP ${response.status}`);
        continue;
      }
      return await response.json();
    } catch (e) {
      clearTimeout(timeoutId);
      if (i === retries) throw e;
      await new Promise(r => setTimeout(r, 1500));
    }
  }
}

export async function lookingGlassRoutes(fastify: FastifyInstance): Promise<void> {
  fastify.get<{ Querystring: LookingGlassQuery }>(
    '/looking-glass',
    async (request: FastifyRequest<{ Querystring: LookingGlassQuery }>, reply: FastifyReply) => {
      const resource = request.query.prefix || request.query.asn || '';
      
      reply.header('Access-Control-Allow-Origin', '*');
      reply.header('Cache-Control', 'no-store');

      if (!resource) {
        return reply.status(400).send({ error: 'prefix or asn required' });
      }

      try {
        const url = `https://stat.ripe.net/data/looking-glass/data.json?resource=${encodeURIComponent(resource)}`;
        const data = await fetchWithRetry(url, 1, 6000);
        
        const rrcs = (data && data.data && data.data.rrcs) || [];
        const results = rrcs.slice(0, 15).map((rrc: any) => ({
          rrc: rrc.rrc,
          location: rrc.location,
          peers: (rrc.peers || []).slice(0, 5).map((p: any) => ({
            asn: p.asn_origin,
            as_path: p.as_path,
            community: p.community,
            next_hop: p.next_hop,
          }))
        }));
        
        return reply.status(200).send({ 
          resource, 
          rrcs: results, 
          total_rrcs: rrcs.length 
        });
      } catch (e: any) {
        return reply.status(500).send({ error: e.message });
      }
    }
  );
}
