import csv


def format_data_as_tsv(tsv_file, snapshot_rows, data_table):
    """ Write BigQuery results into a TSV file for importing to Terra.
    The first row header must follow the format 'entity:{data_table}_id'.
    For example, 'entity:sample_id' will upload the tsv data into a "sample" table in
    the workspace (or create one if it does not exist). If the table already contains
    a sample with that id, it will get overwritten."""
    entities = []
    with open(tsv_file, 'w') as f:
        headers = None
        writer = csv.writer(f, delimiter='\t')
        for row in snapshot_rows:
            if not headers:
                keys = list(row.keys())
                keys[0] = f'entity:{data_table}_id'
                writer.writerow(keys)
            writer.writerow(row.values())
            entities.append({'entity_name': data_table, "entity_id": row[0]})
    return entities