WITH values AS (
  SELECT
    4096/(ceil(pg_settings.setting::numeric/1024/1024))::int AS segment_parts_count,
    setting::bigint AS segment_size,
    ('x' || substring(pg_stat_archiver.last_archived_wal from 9 for 8))::bit(32)::int AS last_wal_div,
    ('x' || substring(pg_stat_archiver.last_archived_wal from 17 for 8))::bit(32)::int AS last_wal_mod,
    CASE WHEN pg_is_in_recovery() THEN NULL 
      ELSE ('x' || substring(pg_walfile_name(pg_current_wal_lsn()) from 9 for 8))::bit(32)::int END AS current_wal_div,
    CASE WHEN pg_is_in_recovery() THEN NULL 
      ELSE ('x' || substring(pg_walfile_name(pg_current_wal_lsn()) from 17 for 8))::bit(32)::int END AS current_wal_mod
  FROM pg_settings, pg_stat_archiver
  WHERE pg_settings.name = 'wal_segment_size')
SELECT json_build_object(
  'archived_count', (SELECT archived_count FROM pg_stat_archiver),
  'failed_count', (SELECT failed_count FROM pg_stat_archiver),
  'count_files', (SELECT greatest(coalesce((segment_parts_count - last_wal_mod) + ((current_wal_div - last_wal_div - 1) * segment_parts_count) + current_wal_mod - 1, 0), 0) FROM values),
  'size_files', (SELECT greatest(coalesce(((segment_parts_count - last_wal_mod) + ((current_wal_div - last_wal_div - 1) * segment_parts_count) + current_wal_mod - 1) * segment_size, 0), 0) FROM values)
) AS result