import type { APIRoute } from 'astro';
import {
  getChoroplethData,
  getNationalStats,
  getCountyStats,
  getUatDetail,
  getFeed,
  getAnnouncementDetail,
  getUatMetric,
  type ChoroplethMetric,
} from '../../../lib/seap-queries.js';

export const prerender = false;

const json = (data: any, status = 200) =>
  new Response(JSON.stringify(data), {
    status,
    headers: {
      'Content-Type': 'application/json',
      'Cache-Control': 'public, max-age=300', // 5 min cache
    },
  });

const error = (msg: string, status = 400) =>
  json({ error: msg }, status);

export const GET: APIRoute = async ({ params }) => {
  const route = params.route || '';
  const parts = route.split('/');

  try {
    // GET /api/harta/stats
    if (route === 'stats') {
      const [national, counties] = await Promise.all([
        getNationalStats(),
        getCountyStats(),
      ]);
      return json({ national, counties });
    }

    // GET /api/harta/choropleth?year=2026
    if (route === 'choropleth') {
      // Year param via URL isn't available here, parse from the full URL
      return json({ error: 'Use /api/harta/choropleth/2026 or /api/harta/choropleth/all' });
    }

    // GET /api/harta/choropleth/:year
    if (parts[0] === 'choropleth') {
      const yearStr = parts[1];
      const year = yearStr === 'all' ? undefined : parseInt(yearStr);
      if (yearStr !== 'all' && (isNaN(year!) || year! < 2007 || year! > 2030)) {
        return error('Year must be between 2007 and 2030, or "all"');
      }
      const data = await getChoroplethData(year);
      return json({ count: data.length, data });
    }

    // GET /api/harta/metric/:metric — multi-mode choropleth (value/direct/hhi/topshare/q4spike)
    if (parts[0] === 'metric' && parts[1]) {
      const metric = parts[1] as ChoroplethMetric;
      if (!['value', 'direct', 'hhi', 'topshare', 'q4spike'].includes(metric)) {
        return error('Invalid metric. Use: value, direct, hhi, topshare, q4spike');
      }
      const data = await getUatMetric(metric);
      return json({ metric, count: data.length, data });
    }

    // GET /api/harta/uat/:siruta
    if (parts[0] === 'uat' && parts[1]) {
      const siruta = parts[1];
      const detail = await getUatDetail(siruta);
      if (!detail.stats) return error('UAT not found', 404);
      return json(detail);
    }

    // GET /api/harta/flows/:siruta — top supplier flows for an authority UAT
    if (parts[0] === 'flows' && parts[1]) {
      const { getUatFlows } = await import('../../../lib/seap-queries.js');
      const data = await getUatFlows(parts[1], 10);
      return json(data);
    }

    // GET /api/harta/feed?limit=20
    if (parts[0] === 'feed') {
      const limit = parseInt(parts[1] || '20');
      const data = await getFeed(Math.min(limit, 100));
      return json(data);
    }

    // GET /api/harta/anunt/:id — single announcement detail
    if (parts[0] === 'anunt' && parts[1]) {
      const detail = await getAnnouncementDetail(parseInt(parts[1]));
      if (!detail) return error('Not found', 404);
      return json(detail);
    }

    // GET /api/harta/mvt/:sourceOrAuto/:z/:x_y — proxy to Martin vector tiles
    if (parts[0] === 'mvt' && parts.length === 4) {
      let source = parts[1];
      const z = parseInt(parts[2]);
      const [x, y] = parts[3].split('_');

      // Auto-select source based on zoom level (matching martin.yaml config)
      if (source === 'auto') {
        if (z < 5) source = 'gis_uats_z0';
        else if (z < 8) source = 'gis_uats_z5';
        else if (z < 12) source = 'gis_uats_z8';
        else source = 'gis_uats_z12';
      }

      const allowed = ['gis_uats_z0', 'gis_uats_z5', 'gis_uats_z8', 'gis_uats_z12'];
      if (!allowed.includes(source)) return error('Invalid source', 400);

      const martinUrl = process.env.MARTIN_URL || 'http://10.10.10.166:3010';
      const tileRes = await fetch(`${martinUrl}/${source}/${z}/${x}/${y}`, {
        headers: { Accept: 'application/x-protobuf' },
      });

      if (!tileRes.ok) return new Response(null, { status: tileRes.status });

      const body = await tileRes.arrayBuffer();

      // Don't forward Content-Encoding — fetch() decompresses automatically
      return new Response(body, {
        status: 200,
        headers: {
          'Content-Type': 'application/x-protobuf',
          'Cache-Control': 'public, max-age=3600',
          'Access-Control-Allow-Origin': '*',
        },
      });
    }

    return error('Unknown route', 404);
  } catch (err: any) {
    console.error(`[API /harta/${route}]`, err);
    return error('Internal server error', 500);
  }
};
