import copy
from yt.wrapper import with_context


def yandexuid_to_yuid_mapper(rec):
    rec['yuid'] = str(rec['yandexuid'])
    del rec['yandexuid']
    yield rec


def unique_reducer(_, recs):
    for rec in recs:
        yield rec
        break


def unite_tables(yt_client, tables, output_table, key):
    yt_client.run_reduce(
        _unite_reducer,
        tables,
        output_table,
        reduce_by=key,
    )


@with_context
def _unite_reducer(_, recs, context):
    res_rec = {}
    for rec in recs:
        if context.table_index == 0:
            res_rec = copy.copy(rec)
        elif res_rec:
            for key, val in rec.items():
                res_rec[key] = val
    yield dict(res_rec)
