"""empty message

Revision ID: 97b7453cbc58
Revises: f2216655ba47
Create Date: 2022-01-25 13:37:51.751485

"""
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 = '97b7453cbc58'
down_revision = 'f2216655ba47'
branch_labels = None
depends_on = None


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

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

# https://st.yandex-team.ru/GEODISPLAY-673
comment = "Новая годовая программа 2022; https://st.yandex-team.ru/GEODISPLAY-673"

products_data = [
    {
        "oracle_id": 513218,
        "title": "Геомедийная программа № 3. Брендированные пины по маршруту в Геосервисах",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "30"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "PIN_ON_ROUTE",
        "cpm_filters": [
            "targeting_type_common_with_audience",
        ],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
    {
        "oracle_id": 513218,
        "title": "Геомедийная программа № 3. Брендированные пины по маршруту в Геосервисах",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "30"},
        "currency": "RUB",
        "platforms": ["MAPS"],
        "campaign_type": "PIN_ON_ROUTE",
        "cpm_filters": [
            "targeting_type_common_with_audience",
        ],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
    {
        "oracle_id": 513253,
        "title": "Геомедийная программа № 3. Билборды по маршруту в Геосервисах",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "20"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "BILLBOARD",
        "cpm_filters": [
            "targeting_type_common_with_audience",
        ],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
    {
        "oracle_id": 513288,
        "title": "Геомедийная программа № 3. Баннер в Навигаторе",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "130"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "ZERO_SPEED_BANNER",
        "cpm_filters": ["targeting_type_common_with_audience", "creative_presence_audio_banner"],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
    {
        "oracle_id": 513254,
        "title": "Геомедийная программа № 3. Баннер в Метро",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "150"},
        "currency": "RUB",
        "platforms": ["METRO"],
        "campaign_type": "ROUTE_BANNER",
        "cpm_filters": [
            "targeting_type_common_with_audience",
        ],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
    {
        "oracle_id": 513220,
        "title": "Геомедийная программа № 3. Баннер при построении маршрута в Яндекс.Навигаторе",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "140"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "OVERVIEW_BANNER",
        "cpm_filters": [
            "targeting_type_common_with_audience",
        ],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
    {
        "oracle_id": 513289,
        "title": "Геомедийная программа № 3. Брендированная иконка в меню поиска в Геосервисах",
        "billing_type": "FIX",
        "billing_data": {"cost": "2100000", "time_interval": "MONTHLY"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "CATEGORY_SEARCH_PIN",
        "cpm_filters": [],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
    {
        "oracle_id": 513289,
        "title": "Геомедийная программа № 3. Брендированная иконка в меню поиска в Геосервисах",
        "billing_type": "FIX",
        "billing_data": {"cost": "2100000", "time_interval": "MONTHLY"},
        "currency": "RUB",
        "platforms": ["MAPS"],
        "campaign_type": "CATEGORY_SEARCH_PIN",
        "cpm_filters": [],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
    {
        "oracle_id": 513255,
        "title": "Геомедийная программа № 3. Рекомендация маршрута в Яндекс.Навигаторе",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "50"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "VIA_POINTS",
        "cpm_filters": [],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
    {
        "oracle_id": 513221,
        "title": "Геомедийная программа № 3. Авто. Рекомендация маршрута в Яндекс.Навигаторе",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "100"},
        "currency": "RUB",
        "platforms": ["NAVI"],
        "campaign_type": "VIA_POINTS",
        "cpm_filters": [],
        "service_id": 110,
        "type": "YEARLONG",
        "min_budget": 0,
    },
]


@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,
                                type
                            )
                            VALUES (
                                :oracle_id,
                                :title,
                                :act_text,
                                :description,
                                :currency,
                                :billing_type,
                                :vat,
                                :campaign_type,
                                :platform,
                                :comment,
                                TRUE,
                                TRUE,
                                (:platforms)::platformtype[],
                                :service_id,
                                :type
                            )
                            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"],
                type=product_data["type"],
            )


def downgrade():
    pass
