"""empty message

Revision ID: 46f4635ac104
Revises: 22e09673984e
Create Date: 2021-02-01 20:54:06.081014

"""
import json
import logging
from datetime import datetime

import pytz

from alembic import op
import sqlalchemy as sa

import maps_adv.billing_proxy.lib.db.columns
import maps_adv.billing_proxy.lib.db.enums

from maps_adv.billing_proxy.lib.db.migration_helpers import data_migration


# revision identifiers, used by Alembic.
revision = '46f4635ac104'
down_revision = '22e09673984e'
branch_labels = None
depends_on = None


_moscow_tz = pytz.timezone("Europe/Moscow")

active_from = _moscow_tz.localize(datetime(2021, 2, 1))
active_to = _moscow_tz.localize(datetime(2022, 1, 31, 23, 59, 59))

# https://st.yandex-team.ru/GEOPROD-5497#601006ebfc49a078560e693f
comment = "Новая годовая программа 2021; https://st.yandex-team.ru/GEODISPLAY-51"

products_data = [
    {
        "oracle_id": 511955,
        "title": "Годовая программа № 13. Брендированные пины по маршруту",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "10"},
        "currency": "RUB",
        "platforms": ["NAVI", "MAPS"],
        "campaign_type": "PIN_ON_ROUTE",
        "cpm_filters": [
            "targeting_type_cascade_except_realty",
        ],
        "service_id": 110,
        "min_budget": 0,
    },
    {
        "oracle_id": 511956,
        "title": "Годовая программа № 13. Билборд по маршруту",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "7"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "BILLBOARD",
        "cpm_filters": [
            "targeting_type_cascade_except_realty",
        ],
        "service_id": 110,
        "min_budget": 0,
    },
    {
        "oracle_id": 511957,
        "title": "Годовая программа № 13. Баннер в Навигаторе",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "100"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "ZERO_SPEED_BANNER",
        "cpm_filters": [
            "targeting_type_common",
            "creative_presence_audio_banner"
        ],
        "service_id": 110,
        "min_budget": 0,
    },
    {
        "oracle_id": 511958,
        "title": "Годовая программа № 13. Баннер в Метро",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "150"},
        "currency": "RUB",
        "platforms": ["METRO"],
        "campaign_type": "ROUTE_BANNER",
        "cpm_filters": [
            "targeting_type_common",
        ],
        "service_id": 110,
        "min_budget": 0,
    },
    {
        "oracle_id": 511959,
        "title": "Годовая программа № 13. Баннер при построении маршрута",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "100"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "OVERVIEW_BANNER",
        "cpm_filters": [
            "targeting_type_common",
        ],
        "service_id": 110,
        "min_budget": 0,
    },
    {
        "oracle_id": 511960,
        "title": "Годовая программа № 13. Брендированная иконка в меню поиска",
        "billing_type": "FIX",
        "billing_data": {"cost": "1200000.00", "time_interval": "MONTHLY"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "CATEGORY_SEARCH_PIN",
        "cpm_filters": [],
        "service_id": 110,
        "min_budget": 0,
    },
    {
        "oracle_id": 511960,
        "title": "Годовая программа № 13. Брендированная иконка в меню поиска",
        "billing_type": "FIX",
        "billing_data": {"cost": "200000", "time_interval": "MONTHLY"},
        "currency": "RUB",
        "platforms": ["MAPS"],
        "campaign_type": "CATEGORY_SEARCH_PIN",
        "cpm_filters": [],
        "service_id": 110,
        "min_budget": 0,
    },
    {
        "oracle_id": 511961,
        "title": "Годовая программа № 13. Рекомендация маршрута",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "50"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "VIA_POINTS",
        "cpm_filters": [],
        "service_id": 110,
        "min_budget": 0,
    },
]

# Connect this client to the IDs below
# BurgerKing
client_id = 39772364

oracle_ids_to_bind = [511955, 511956, 511957, 511958, 511959, 511960, 511961]

@data_migration
def upgrade():
    con = op.get_bind()

    product_oracle_ids = set(
        product_data["oracle_id"] for product_data in products_data
    )
    cursor = con.execute(
        sa.text(
            """
            SELECT EXISTS (
                SELECT
                FROM products
                WHERE oracle_id IN :oracle_ids
            )
        """
        ),
        oracle_ids=tuple(product_oracle_ids),
    )
    any_product_exists = cursor.scalar()
    if any_product_exists:
        logging.getLogger("alembic.runtime.migration").warning(
            "Found products with one of oracle_ids mentioned, skipping revision."
        )
        return

    for product_data in products_data:
        for platform in product_data["platforms"]:
            con.execute(
                sa.text(
                    """
                    WITH
                        inserted_product AS (
                            INSERT INTO products (
                                oracle_id,
                                title,
                                act_text,
                                description,
                                currency,
                                billing_type,
                                vat_value,
                                campaign_type,
                                platform,
                                comment,
                                available_for_agencies,
                                available_for_internal,
                                platforms,
                                service_id
                            )
                            VALUES (
                                :oracle_id,
                                :title,
                                :act_text,
                                :description,
                                :currency,
                                :billing_type,
                                :vat,
                                :campaign_type,
                                :platform,
                                :comment,
                                TRUE,
                                TRUE,
                                (:platforms)::platformtype[],
                                :service_id
                            )
                            RETURNING id
                        ),
                        inserted_version AS (
                            INSERT INTO product_rules_versions (
                                product_id,
                                version,
                                active_from,
                                active_to,
                                billing_data,
                                min_budget,
                                cpm_filters
                            )
                            SELECT id,
                                   1,
                                   :active_from,
                                   :active_to,
                                   :billing_data,
                                   :min_budget,
                                   :cpm_filters
                            FROM inserted_product
                        )
                    SELECT 1
                    """  # noqa: E501
                ),
                comment=comment,  # noqa: E501
                currency="RUB",
                vat=0.2,
                oracle_id=product_data["oracle_id"],
                title=product_data["title"],
                act_text=product_data["title"],
                description="{} {}".format(
                    product_data["oracle_id"], product_data["title"]
                ),
                billing_type=product_data["billing_type"],
                campaign_type=product_data["campaign_type"],
                platform=platform,
                platforms=[platform],
                active_from=active_from,
                active_to=active_to,
                billing_data=json.dumps(product_data["billing_data"]),
                cpm_filters=product_data["cpm_filters"],
                min_budget=product_data["min_budget"],
                service_id=product_data["service_id"],
            )

    con.execute(
        sa.text(
            """
        WITH product AS (
            SELECT * FROM products WHERE oracle_id IN :oracle_ids
        )
        INSERT INTO product_client_restrictions (product_id, client_id)
        SELECT id, :client_id
        FROM product
        """
        ),
        oracle_ids=tuple(oracle_ids_to_bind),
        client_id=client_id,
    )



def downgrade():
    pass
