use hahn;

$capture_yuid = Re2::Capture(".*yandexUid=(\\d+).*");
$capture_uid = Re2::Capture(".*userId=(\\d+).*");

--  https://lab.crypta.yandex-team.ru/segments?group=group-01f9d150&segment=segment-c54a79ec
$crypta_yuids = (
    select distinct yandexuid
    from `//home/crypta/production/profiles/export/profiles_for_14days`
    where ListHas(Yson::ConvertToInt64List(heuristic_internal), 2027)
        or ListHas(Yson::ConvertToInt64List(audience_segments), 17570290)
);

$webmaster_uids = (
    select yandexuid, UserId
    from range(`//home/webmaster/prod/analytics/logs/qloud/front/app`, `2020-08-01`)
    where message like "%yandexUid=%"
        and message like "%userId=%"
    group by 
        cast($capture_yuid(message)._1 as UInt64) as yandexuid,
        cast($capture_uid(message)._1 as UInt64) as UserId
);

$crypta_webmaster_uids = (
    select distinct UserId
    from $webmaster_uids as w
    inner join $crypta_yuids as c
        on w.yandexuid == c.yandexuid
);

select UserId, Email
from `//home/webmaster/prod/analytics/mailings/base` 
where UserId in $crypta_webmaster_uids
    and LanguageRU
    and not IsEuropeanUser
    and GLOBAL_NOTIFICATION
group by UserId, Email
order by UserId, Email
