WITH base AS (
  SELECT
    * REPLACE (normalized_channel AS channel),
    (attribution.source IS NOT NULL OR attribution.campaign IS NOT NULL) AS attributed
  FROM
    `moz-fx-data-shared-prod.telemetry.clients_last_seen`
),
  --
nested AS (
  SELECT
    submission_date,
    [
      STRUCT(
        'Any Firefox Desktop Activity' AS usage,
        `moz-fx-data-shared-prod.udf.smoot_usage_from_28_bits`(
          ARRAY_AGG(STRUCT(days_created_profile_bits, days_seen_bits))
        ) AS metrics
      ),
      STRUCT(
        'Firefox Desktop Visited 5 URI' AS usage,
        `moz-fx-data-shared-prod.udf.smoot_usage_from_28_bits`(
          ARRAY_AGG(STRUCT(days_created_profile_bits, days_visited_5_uri_bits))
        ) AS metrics
      ),
      STRUCT(
        'Firefox Desktop Opened Dev Tools' AS usage,
        `moz-fx-data-shared-prod.udf.smoot_usage_from_28_bits`(
          ARRAY_AGG(STRUCT(days_created_profile_bits, days_opened_dev_tools_bits))
        ) AS metrics
      )
    ] AS metrics_array,
    MOD(ABS(FARM_FINGERPRINT(client_id)), 20) AS id_bucket,
    app_name,
    app_version,
    country,
    locale,
    os,
    os_version,
    channel,
    attributed
  FROM
    base
  WHERE
    client_id IS NOT NULL
    -- Reprocess all dates by running this query with --parameter=submission_date:DATE:NULL
    AND (@submission_date IS NULL OR @submission_date = submission_date)
  GROUP BY
    submission_date,
    id_bucket,
    app_name,
    app_version,
    country,
    locale,
    os,
    os_version,
    channel,
    attributed
)
  --
SELECT
  submission_date,
  m.usage,
  (SELECT AS STRUCT m.metrics.* EXCEPT (is_empty_group)) AS metrics,
  nested.* EXCEPT (submission_date, metrics_array)
FROM
  nested
CROSS JOIN
  UNNEST(metrics_array) AS m
WHERE
  -- Optimization so we don't have to store rows where counts are all zero.
  NOT m.metrics.is_empty_group
