SELECT
  latest.id, latest.region_id, latest.price_mwh, latest.demand_mw,
  latest.timestamp, latest.source,
  r.code as region_code, r.name as region_name,
  stats.avg_price_7d, stats.stddev_price_7d
FROM (
  SELECT DISTINCT ON (ep.region_id)
    ep.id, ep.region_id, ep.price_mwh, ep.demand_mw, ep.timestamp, ep.source
  FROM electricity_prices ep
  ORDER BY ep.region_id, ep.timestamp DESC
) latest
JOIN grid_regions r ON latest.region_id = r.id
LEFT JOIN LATERAL (
  SELECT
    AVG(ep2.price_mwh)::double precision as avg_price_7d,
    STDDEV(ep2.price_mwh)::double precision as stddev_price_7d
  FROM electricity_prices ep2
  WHERE ep2.region_id = latest.region_id
    AND ep2.timestamp >= NOW() - INTERVAL '7 days'
) stats ON true
