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