SELECT
  r.code, r.name,
  ST_AsGeoJSON(r.boundary)::TEXT as boundary_geojson,
  AVG(ep.price_mwh) as avg_price,
  MAX(ep.price_mwh) as max_price,
  AVG(ep.demand_mw) as avg_demand,
  COUNT(DISTINCT d.id)::INT as datacenter_count,
  COALESCE(SUM(d.capacity_mw), 0) as total_dc_capacity_mw
FROM grid_regions r
LEFT JOIN electricity_prices ep ON ep.region_id = r.id
  AND ep.timestamp > NOW() - INTERVAL '24 hours'
LEFT JOIN datacenters d ON d.region_id = r.id
GROUP BY r.id, r.code, r.name, r.boundary
