from maps.wikimap.stat.tasks_payment.dictionaries.holidays.lib.holidays import (
    HOLIDAYS_SCHEMA,
    get_holidays,
)
from maps.wikimap.stat.tasks_payment.dictionaries.libs.oebs_api import (
    OEBS_ENV_PROD,
    OEBS_ENV_TEST,
)

import yt.wrapper as yt

import argparse
import datetime
from textwrap import dedent


_CLIENT_ID = 2033341


def parse_args():
    parser = argparse.ArgumentParser(
        description=dedent('''\
            Calculates holidays dictionaries.

            Dictionaries are generated for each person in the staff dump. Information
            about holidays is taken from OEBS.

            Note. The generated dictionary is stored on the Hahn YT cluster. The token to
            connect to the cluster must be provided either by means of YT_TOKEN environment
            variable or `~/.yt/token` file.
        '''),
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument(
        '--tvm-secret',
        help='TVM client secret. (see https://abc.yandex-team.ru/services/nmaps_oebs_integration/resources/?show-resource=41376779)',
        required=True
    )
    parser.add_argument(
        '--date',
        help='Date (YYYY-MM-DD) dictionary must be calculated for.',
        type=datetime.date.fromisoformat,
        required=True
    )
    parser.add_argument(
        '--env',
        help='OEBS environment: %(choices)s. (default: %(default)s)',
        choices=[OEBS_ENV_PROD, OEBS_ENV_TEST],
        default=OEBS_ENV_TEST
    )

    return parser.parse_args()


def read_logins(yt_client, staff_dump_dir, date):
    staff_dump = yt_client.read_table(yt.ypath_join(staff_dump_dir, date))
    return [record['login'] for record in staff_dump]


def write_holidays(yt_client, holidays_dir, date, holidays):
    path = yt.ypath_join(holidays_dir, date)
    yt_client.create(
        "table", path, ignore_existing=True, recursive=True,
        attributes={"schema": HOLIDAYS_SCHEMA}
    )
    yt_client.write_table(path, holidays)


def main():
    args = parse_args()

    yt_client = yt.YtClient("hahn", config=yt.default_config.get_config_from_env())

    logins = read_logins(
        yt_client,
        '//home/maps/core/nmaps/analytics/tasks_payment/dictionaries/staff_dump',
        args.date.isoformat()
    )
    holidays = get_holidays(args.env, _CLIENT_ID, args.tvm_secret, logins, args.date)
    write_holidays(
        yt_client,
        '//home/maps/core/nmaps/analytics/tasks_payment/dictionaries/holidays',
        args.date.isoformat(),
        holidays
    )
