import maps.wikimap.stat.kpi.poi_stat.lib.altay as altay
import maps.wikimap.stat.kpi.poi_stat.lib.poi_stat as poi_stat
import maps.wikimap.stat.kpi.poi_stat.lib.ymapsdf as ymapsdf
import yt.wrapper as yt

from nile.api.v1 import (
    cli,
    clusters,
    Job
)

import datetime

MAJOR_REGIONS_PATH: str = '//home/maps/core/nmaps/analytics/geo-data/major_regions_map'

JOB_OPTIONS = [
    cli.Option(
        'result-path',
        help='Path to YT directory for storing result tables with daily POI stat.',
        required=False
    ),
    cli.Option(
        'recalculate',
        help='Set this flag to recalculate metrics for a given date.',
        required=False,
        is_flag=True
    ),
]


@cli.statinfra_job(options=JOB_OPTIONS)
def make_job(job: Job, options) -> Job:
    cluster = clusters.yql.Hahn()
    yt.config.set_proxy(cluster.proxy)

    date = ''
    raw_data = None
    if options.recalculate:
        date = options.dates[0]
        raw_data = job.table(yt.ypath.ypath_join(options.result_path, 'raw', date))
    else:
        date = datetime.date.today().isoformat()

        ymapsdf_paths = ymapsdf.ymapsdf_latest_paths()
        ft = ymapsdf.ymapsdf_table(job, ymapsdf_paths, 'alpha', 'ft', 'ft_id')
        ft_poi_attr = ymapsdf.ymapsdf_table(job, ymapsdf_paths, 'alpha', 'ft_poi_attr', 'ft_id')
        ft_center = ymapsdf.ymapsdf_table(job, ymapsdf_paths, 'alpha', 'ft_center', 'ft_id')
        node = ymapsdf.ymapsdf_table(job, ymapsdf_paths, 'alpha', 'node', 'node_id')

        altay_data = altay.altay_data_table(job)

        ft_source = ymapsdf.ymapsdf_table(
            job, ymapsdf_paths, 'final', 'ft_source', 'ft_id', 'source_type_id')

        raw_data = poi_stat.make_raw_data(ft, ft_poi_attr, ft_center, node, altay_data, ft_source)
        raw_data.put(yt.ypath.ypath_join(options.result_path, 'raw', date))

    major_regions = job.table(MAJOR_REGIONS_PATH)
    poi_stat.calculate_stat(job, raw_data, major_regions, options.result_path, date)

    return job


def main() -> None:
    cli.run()


if __name__ == '__main__':
    main()
