import csv


def category_totals(rows):
    totals = {}
    for row in rows:
        if None in row or row['category'] is None or row['amount_cents'] is None:
            raise ValueError('Each expense needs exactly two fields.')
        category = row['category'].strip()
        if category == '':
            raise ValueError('Each expense needs a category.')
        amount = int(row['amount_cents'])
        if amount < 0:
            raise ValueError('This purchase report expects nonnegative amounts.')
        if category in totals:
            totals[category] = totals[category] + amount
        else:
            totals[category] = amount
    return totals


def format_totals(totals):
    if totals == {}:
        return 'No expenses.\n'
    report = ''
    for category in totals:
        report = report + f'{category}: {totals[category]} cents\n'
    return report


def main():
    with open('expenses.csv', newline='', encoding='utf-8') as source:
        rows = csv.DictReader(source)
        if rows.fieldnames != ['category', 'amount_cents']:
            raise ValueError('Expected the header: category,amount_cents')
        totals = category_totals(rows)

    report = format_totals(totals)
    print('Report preview:')
    print(report, end='')
    answer = input('Save this as expense_totals.txt? (yes/no) ')
    if answer == 'yes':
        with open('expense_totals.txt', 'w', encoding='utf-8') as destination:
            destination.write(report)
        print('Saved expense_totals.txt.')
    else:
        print('Preview finished without saving.')


if __name__ == '__main__':
    main()
