# flake8: noqa

__all__ = [
    "import_promotions",
    "import_service_lists",
    "import_services",
    "import_ctas",
    "import_call_tracking",
]

BIZ_IDS_QUERY = """
    $biz_ids = (
        SELECT
            MIN(gco.campaign_id) as biz_id,
            gco.permalink as permalink
        FROM {yt_cluster}.`{geadv_orgs_yt_table}` as gco
        INNER JOIN {yt_cluster}.`{geoadv_campaigns_yt_table}` as gc
            ON gco.campaign_id = gc.id
        WHERE Yson::ConvertToString(gc.type) = 'SMBCRM'
        GROUP BY gco.permalink as permalink
    );
"""

YSON_DISABLE_STRICT = """
    pragma yson.disablestrict;
"""

import_promotions = (
    YSON_DISABLE_STRICT
    + BIZ_IDS_QUERY
    + """
    SELECT
        adv.advert_id,
        geo_data.biz_id,
        Yson::LookupString(adv.advert_body, 'announcement'),
        Yson::LookupString(adv.advert_body, 'description'),
        Yson::LookupString(adv.advert_body, 'date_from'),
        Yson::LookupString(adv.advert_body, 'date_to'),
        Yson::LookupString(COALESCE(Yson::Lookup(adv.advert_body, 'image'),
                                    Yson::Lookup(adv.advert_body, 'user_squared_image')),
                           'href'),
        CASE WHEN Yson::LookupString(adv.advert_body, 'link') = ''
            THEN NULL
            ELSE Yson::LookupString(adv.advert_body, 'link')
        END
    FROM {yt_cluster}.`{source_table}` as adv
    INNER JOIN $biz_ids as geo_data ON geo_data.permalink = adv.permalink
    WHERE adv.advert_type = 'PROMOTION';
    """
)


import_ctas = (
    BIZ_IDS_QUERY
    + """
    $cta_adverts = (
        SELECT permalink, advert_id
        , Yson::YPathString(advert_body, '/link') as link
        , Yson::YPathString(advert_body, '/title') as title
        FROM {yt_cluster}.`{source_table}`
        WHERE advert_type = 'CLICK_TO_ACTION'
    );

    SELECT adv.advert_id as advert_id
    , biz.biz_id as biz_id
    , adv.title as title
    , if(adv.link != '', adv.link, '{base_widget_request_url}/' || cast(biz.permalink as String)) as link
    FROM $biz_ids as biz
    JOIN $cta_adverts as adv on adv.permalink = biz.permalink
    """
)

import_service_lists = (
    BIZ_IDS_QUERY
    + """
    SELECT
        adv.advert_id,
        geo_data.biz_id,
        ListMap(
           Yson::LookupList(adv.advert_body, 'product_ids'),
            ($id) -> {{
                RETURN Yson::ConvertToInt64($id, Yson::Options(true as AutoConvert));
            }}
        )
    FROM {yt_cluster}.`{source_table}` as adv
    INNER JOIN $biz_ids as geo_data ON geo_data.permalink = adv.permalink
    WHERE adv.advert_type = 'PRODUCT_LIST';
    """
)

import_services = (
    YSON_DISABLE_STRICT
    + BIZ_IDS_QUERY
    + """
    SELECT
        adv.advert_id,
        geo_data.biz_id,
        Yson::LookupString(adv.advert_body, 'title'),
        Yson::LookupString(adv.advert_body, 'price'),
        Yson::LookupString(Yson::Lookup(adv.advert_body, 'image'), 'href'),
        Yson::LookupString(adv.advert_body, 'url'),
        Yson::LookupString(adv.advert_body, 'text')
    FROM {yt_cluster}.`{source_table}` as adv
    INNER JOIN $biz_ids as geo_data ON geo_data.permalink = adv.permalink
    WHERE adv.advert_type = 'PRODUCT';
    """
)

import_call_tracking = (
    BIZ_IDS_QUERY
    + """
    SELECT
        adv.advert_id,
        geo_data.biz_id,
        Yson::LookupString(Yson::Lookup(adv.advert_body, 'tracking'), 'formatted')
    FROM {yt_cluster}.`{source_table}` as adv
    INNER JOIN $biz_ids as geo_data ON geo_data.permalink = adv.permalink
    WHERE adv.advert_type = 'CALL_TRACKING' AND adv.advert_body IS NOT NULL;
    """
)

import_google_counters = """
    SELECT permalink, AGGREGATE_LIST(AsStruct(counter_id as id, goals as goals)) FROM (
        SELECT
            permalink,
            counter_id,
            ToDict(AGGREGATE_LIST(AsTuple(event_name, event_id))) as goals
        FROM {yt_cluster}.`{source_table}`
        GROUP BY permalink, counter_id
    )
    GROUP BY permalink
    """

import_avatars = """
    SELECT source_url, avatars_group_id, avatars_name
    FROM {yt_cluster}.`{geoadv_base_yt_prefix}/stream_snapshots/arbitrage_photo`
    WHERE Yson::ConvertToString(source_type) = 'site'
    AND avatars_group_id IS NOT NULL
    """

import_market_int_services = """
$service_categories_active =
    SELECT
        service_categories.name AS category_name,
        service_categories_services.service_id as service_id
    FROM {yt_cluster}.`{market_int_streaming_folder}/service_categories` AS service_categories
    LEFT JOIN {yt_cluster}.`{market_int_streaming_folder}/service_categories_services` AS service_categories_services
        ON service_categories_services.category_id = service_categories.id
    WHERE service_categories.deleted = false;

$service_prices =
    SELECT 
        MIN(service_prices.duration_minutes) AS duration_minutes,
        MIN(service_prices.price) AS price,
        service_prices.service_id as service_id
    FROM {yt_cluster}.`{market_int_streaming_folder}/service_prices` AS service_prices
    GROUP BY service_prices.service_id;

$main_image_url_templates =
    SELECT 
        services.gallery_id as gallery_id,
        MIN_BY(url_template, ordering) AS url_template
    FROM {yt_cluster}.`{market_int_streaming_folder}/images` as images
    JOIN {yt_cluster}.`{market_int_streaming_folder}/services` as services
        ON images.gallery_id = services.gallery_id
    GROUP BY services.gallery_id;

$category_names =
    SELECT
        service_id,
        AGGREGATE_LIST(category_name) as category_names
    FROM $service_categories_active
    GROUP BY service_id;

$services = 
    SELECT 
        services.id AS id,
        services.biz_id AS biz_id,
        services.name AS name,
        services.description AS description,
        category_names.category_names AS categories,
        service_prices.price AS min_cost,
        service_prices.duration_minutes AS min_duration,
        services.client_action AS action_type,
        main_image_url_templates.url_template AS image,
        services.status AS status
    FROM {yt_cluster}.`{market_int_streaming_folder}/services` as services
    LEFT JOIN $service_prices AS service_prices 
        ON services.id = service_prices.service_id
    LEFT JOIN $main_image_url_templates AS main_image_url_templates 
        ON services.gallery_id = main_image_url_templates.gallery_id
    LEFT JOIN $category_names as category_names 
        ON services.id = category_names.service_id;

SELECT
    id,
    biz_id,
    name,
    description,
    categories,
    min_cost,
    min_duration,
    action_type,
    image
FROM $services WHERE status = 2; -- PUBLISHED
    """

import_tiktok_pixels = """
    SELECT permalink, AGGREGATE_LIST(AsStruct(tiktok_pixel_id as id, goals as goals)) FROM (
        SELECT
            permalink,
            tiktok_pixel_id,
            ToDict(AGGREGATE_LIST(AsTuple(goal_name, pixel_event_name))) as goals
        FROM {yt_cluster}.`{source_table}`
        GROUP BY permalink, tiktok_pixel_id
    )
    GROUP BY permalink
    """

import_goods_data = """
$by_num_of_items_others_last = ($x) -> {{
    RETURN IF ($x.0 = '__$OTHERS$__', 0, $x.1)
}};

$collapse_categories = ($x) -> {{
    RETURN ListExtend(
        ListTake($x, 10), -- take 10 with most number of items
        [('__$OTHERS$__', 0)] -- append special category for the rest of goods
    )
}};

$categories = SELECT
    company_permalink as permalink,
    IF(group_name IS NULL OR group_name = "", '__$OTHERS$__', group_name) AS category
FROM {yt_cluster}.`{yt_goods_table}` as d
RIGHT JOIN (SELECT DISTINCT permalink FROM {yt_cluster}.`{yt_biz_state_table}` WHERE published) AS b
ON CAST(b.permalink AS Int64) = d.company_permalink
where source = '{source}' AND Yson::ConvertToString(status) <> 'Deleted';

$categories_with_num = SELECT
    permalink,
    AsTuple(category, count(*)) AS cat
FROM $categories
GROUP BY permalink, category;

$groupped_categories = SELECT
    permalink,
    ListSortDesc(AGGREGATE_LIST(cat), $by_num_of_items_others_last) AS categories
FROM $categories_with_num
GROUP BY permalink;

$selected_categories = SELECT
    permalink,
    IF(
        ListLength(categories) <= 10,
        categories,
        $collapse_categories(categories)
    ) AS categories
FROM $groupped_categories;

SELECT
    permalink,
    ListMap(categories, ($x) -> {{RETURN $x.0;}}) AS categories
FROM $selected_categories;
    """

import_vk_pixels = """
    SELECT permalink, AGGREGATE_LIST(AsStruct(vk_pixel_id as id, goals as goals)) FROM (
        SELECT
            permalink,
            vk_pixel_id,
            ToDict(AGGREGATE_LIST(AsTuple(goal_name, pixel_event_name))) as goals
        FROM {yt_cluster}.`{source_table}`
        GROUP BY permalink, vk_pixel_id
    )
    GROUP BY permalink
    """

sync_permalinks = """
    select biz_id, bs.permalink as permalink
    from {yt_cluster}.`{landlord_base_yt_prefix}/streaming_snapshots/biz_state` as ll
    join {yt_cluster}.`{geoadv_base_yt_prefix}/stream_snapshots/geoadv_business_snapshot` as bs on bs.campaign_id = ll.biz_id
    where bs.permalink != 0
    and (ll.permalink = '0' or (cast(ll.permalink as int64) = bs.id and bs.id != bs.permalink));
    """

