from qb2.api.v1 import (
    extractors as qe,
    filters as qf,
    typing,
)


def convert_staff_uid_to_puid(issues, linked_accounts):
    '''
    issues:
    | staff_uid | component | ticket | story_points | date |
    |-----------+-----------+--------+--------------+------|
    | ...       | ...       | ...    | ...          | .... |

    linked_accounts:
    | date | staff_uid | puid | is_primary_link | ... |
    |------+-----------+------+-----------------+-----|
    | ...  | ...       | ...  | ...             | ... |

    Result:
    | puid | component | ticket | story_points | date |
    |------+-----------+--------+--------------+------|
    | ...  | ...       | ...    | ...          | ...  |
    '''

    staff_uid_to_puid = linked_accounts.filter(
        qf.equals('is_primary_link', True)
    ).project(
        'staff_uid',
        'puid',
        'date',
    )

    return issues.join(
        staff_uid_to_puid,
        by=('staff_uid', 'date'),
        type='left',
    ).project(
        'component',
        'ticket',
        'story_points',
        'date',
        qe.or_('puid', 'puid', 'staff_uid').with_type(typing.Optional[typing.Int64]),
        # Let's write staff uid if puid has not been found.
        # This uid most likely will be reflected in the report
        # in all/unknown section.
    )
