# -*- coding: utf-8 -*-
from yt.wrapper import OperationsTracker

from datacloud.dev_utils.solomon.solomon_utils import post_sensors_to_solomon, str2ts
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.stability.crypta_stability.constants import (
    HASH_PHONE_TO_CID_Q, HASH_EMAIL_TO_CID_Q, YUID_TO_CID_Q,
    HASH_PHONE_TO_CID_LAST, HASH_EMAIL_TO_CID_LAST, YUID_TO_CID_LAST,
    DEFAULT_TAG, TMP_FOLDER, UNIQUE_CIDS_Q, UNIQUE_CIDS_LAST,
    SOLOMON_PROJECT, SOLOMON_CLUSTER, CIDS_SERVICE
)
from datacloud.stability.crypta_stability.helpers import (
    join_cids_with_cids, reduce_unique_cids, get_creation_date
)
from datacloud.stability.crypta_stability.tables import cids_log_table


logger = get_basic_logger(__name__)


def upload_cids_stable_to_solomon(crypta_date, is_lost, value):
    sensors = [{
        'labels': {
            'lost': is_lost,
        },
        'ts': str2ts(crypta_date),
        'value': value
    }]
    post_sensors_to_solomon(SOLOMON_PROJECT, SOLOMON_CLUSTER, CIDS_SERVICE, sensors)


def check_cids_stability(yt_client, tag=DEFAULT_TAG):
    with yt_client.Transaction(), yt_client.TempTable(TMP_FOLDER) as i_cids:
        tracker = OperationsTracker()

        op1 = reduce_unique_cids(
            yt_client=yt_client,
            input_paths=[HASH_PHONE_TO_CID_Q, HASH_EMAIL_TO_CID_Q, YUID_TO_CID_Q],
            result=UNIQUE_CIDS_Q,
            tag=tag,
            sync=False
        )
        tracker.add(op1)

        op2 = reduce_unique_cids(
            yt_client=yt_client,
            input_paths=[HASH_PHONE_TO_CID_LAST, HASH_EMAIL_TO_CID_LAST, YUID_TO_CID_LAST],
            result=UNIQUE_CIDS_LAST,
            tag=tag,
            sync=False
        )
        tracker.add(op2)

        tracker.wait_all()

        cids_q = yt_client.row_count(UNIQUE_CIDS_Q)
        cids_last = yt_client.row_count(UNIQUE_CIDS_LAST)

        yt_client.run_map_reduce(
            None,
            join_cids_with_cids,
            [
                yt_client.TablePath(UNIQUE_CIDS_Q, columns=['cid']),
                yt_client.TablePath(UNIQUE_CIDS_LAST, columns=['cid']),
            ],
            i_cids,
            reduce_by='cid',
            spec={'title': '[{}] get cids intersection'.format(tag)}
        )
        cids_intersection = yt_client.row_count(i_cids)

        log_table = cids_log_table.CryptaStabilityCidsTable()
        lost_value = float(cids_last - cids_intersection) / cids_last
        gained_value = float(cids_q - cids_intersection) / cids_q
        crypta_date = get_creation_date(yt_client, HASH_EMAIL_TO_CID_Q)

        log_table.add_record(
            crypta_date=crypta_date,
            cids_last=cids_last,
            cids_q=cids_q,
            cids_intersection=cids_intersection,
            cids_lost=lost_value,
            cids_gained=gained_value
        )
        upload_cids_stable_to_solomon(crypta_date, True, lost_value)
        upload_cids_stable_to_solomon(crypta_date, False, gained_value)
