from maps.wikimap.stat.libs.nile_utils import (
    get_tables_with_names,
    put_tables_by_prefixes,
)
from maps.wikimap.stat.tasks_payment.tasks_logging.libs.schema import CARTOGRAPHIC_TASKS_LOG_SCHEMA
from maps.wikimap.stat.tasks_payment.tasks_logging.tracker.cartographic_log.lib.cartographic_log import make_tracker_cartographic_log

from nile.api.v1 import cli
from yt.wrapper.ypath import ypath_join

from dateutil import tz, utils, parser
import datetime


MAPSPW_DIR = '//home/startrek/tables/prod/yandex-team/queue/maps-pw'


def from_isotime(value, default_tz='Europe/Moscow'):
    tz_info = tz.gettz(default_tz)
    return utils.default_tzinfo(parser.isoparse(value), tz_info)


def check_tracker_replica_freshness(driver, options):
    if options.skip_tracker_replica_freshness_check:
        return

    max_modification_time = max([
        from_isotime(driver.get_attribute(ypath_join(MAPSPW_DIR, table_name), 'modification_time'))
        for table_name in driver.list(MAPSPW_DIR)
    ])
    max_calc_date = max_modification_time.date() - datetime.timedelta(days=1)
    for date in options.dates:
        assert from_isotime(date).date() <= max_calc_date, \
            f'YT Tracker replica {MAPSPW_DIR} is not fresh enough to calculate '\
            f'log for {date}, replica was modified at {max_modification_time}. '\
            f'Information for the whole day is needed to calculate the log.'


@cli.statinfra_job(
    initial_action=check_tracker_replica_freshness,
    options=[cli.Option('skip-tracker-replica-freshness-check', is_flag=True)]
)
def make_job(job, options):
    linked_accounts = get_tables_with_names(
        job,
        '//home/maps/core/nmaps/analytics/tasks_payment/dictionaries/linked_accounts',
        'date', options.dates
    )

    make_tracker_cartographic_log(
        options.dates,
        linked_accounts,
        job.table(ypath_join(MAPSPW_DIR, 'components')),
        job.table(ypath_join(MAPSPW_DIR, 'issue_events')),
        job.table(ypath_join(MAPSPW_DIR, 'issues')),
        job.table('//home/startrek/tables/prod/yandex-team/common/resolutions'),
        job.table('//home/startrek/tables/prod/yandex-team/common/statuses'),
    ).call(
        put_tables_by_prefixes,
        '//home/maps/core/nmaps/analytics/tasks_payment/tasks_logs/tracker_log/',
        'iso_datetime', options.dates,
        CARTOGRAPHIC_TASKS_LOG_SCHEMA,
    )

    return job


def main():
    cli.run()
