from maps.wikimap.stat.common.create_geo_data.lib import (
    regions as r,
    cli
)

import yt.wrapper as yt
from yt.wrapper.ypath import ypath_join


def make_regions(client):
    regions = r.collect_all_regions(client)

    r.update_major_data(regions)
    r.update_facets_population(regions)

    return regions


def upload_table(client, records, schema, path):
    table = yt.TablePath(path, attributes={'schema': schema})
    client.write_table(
        table,
        records,
        format='<encode_utf8=%true>json'
    )


def upload_major_regions_map(client, regions, results_path):
    def generate_records():
        for region_id in regions:
            for region_datum in r.all_majors_for_region(regions, region_id):
                yield region_datum

    upload_table(
        client,
        generate_records(),
        r.ALL_MAJORS_FOR_REGION_SCHEMA,
        ypath_join(results_path, 'major_regions_map'),
    )


def upload_major_regions_info(client, regions, results_path):
    def generate_records():
        for region_id in regions:
            if not regions[region_id]['is_facet']:
                yield r.get_region_info(regions, region_id)

    upload_table(
        client,
        generate_records(),
        r.REGIONS_INFO_SCHEMA,
        ypath_join(results_path, 'major_regions_info'),
    )


def main():
    parser = cli.make_parser()
    args = parser.parse_args()

    client = yt.YtClient(
        proxy=args.proxy,
        config={"tabular_data_format": "json"},
        token=args.token
    )

    regions = make_regions(client)
    upload_major_regions_map(client, regions, args.results)
    upload_major_regions_info(client, regions, args.results)


if __name__ == "__main__":
    main()
