create or replace function ems.fn_latest_ote_day_stats()
returns jsonb
language sql
stable
as $fn$
  select to_jsonb(sub)
  from (
    select
      (mip.interval_start at time zone 'Europe/Prague')::date as latest_date,
      count(*)::int as slots,
      min(mip.buy_raw_price_czk_kwh)::float as min_price,
      max(mip.buy_raw_price_czk_kwh)::float as max_price,
      avg(mip.buy_raw_price_czk_kwh)::float as avg_price
    from ems.market_interval_price mip
    where mip.market_source in ('OTE_CZ', 'OTE_CZ_DAM')
    group by (mip.interval_start at time zone 'Europe/Prague')::date
    order by latest_date desc
    limit 1
  ) sub;
$fn$;

comment on function ems.fn_latest_ote_day_stats() is
  'Agregace posledního kalendářního dne s OTE daty (globální, bez site_id).';
