-- @query people_list_v2
-- @db media 22.0
-- @with photos_only
-- @end-with
-- @with entity_filter
-- @param entity_ids TEXT
-- @end-with
SELECT
    re.primaryEntityId AS entity_id,
    COUNT(DISTINCT rel.driveItemId) AS photo_count,
    MAX(CASE WHEN re.entityId = re.primaryEntityId THEN re.isPinned ELSE 0 END) AS is_pinned,
    MAX(CASE WHEN re.entityId = re.primaryEntityId THEN re.isHidden ELSE 0 END) AS is_hidden,
    MAX(CASE WHEN re.entityId = re.primaryEntityId THEN re.displayName END) AS display_name,
    MAX(CASE WHEN re.entityId = re.primaryEntityId THEN re.representativeItemId END) AS representative_item_id,
    MAX(CASE WHEN re.entityId = re.primaryEntityId THEN re.coverPhotoId END) AS cover_photo_id
FROM media.recognized_entities AS re
JOIN recognized_entity_lookup AS rel ON rel.entityId = re.entityId
JOIN media.media_properties AS cloud ON rel.driveItemId = cloud.driveItemId
JOIN media.media_libraries AS drive ON cloud.driveId = drive.driveId
WHERE cloud.isTombstoned = 0
  AND drive.libraryType = 'Gallery'
  AND cloud.takenDateTime IS NOT NULL
  -- @with photos_only
  AND cloud.photo IS NOT NULL
  AND cloud.video IS NULL
  -- @end-with
  -- @with entity_filter
  AND re.primaryEntityId IN (SELECT value FROM json_each(?entity_ids))
  -- @end-with
GROUP BY re.primaryEntityId
ORDER BY photo_count DESC
