"""Count successful WriteFile requests to nvlog.nvlgstg in a Procmon CSV."""

import argparse
import csv
import re
from pathlib import Path, PureWindowsPath


def summarize(rows):
    required = {'Path', 'Operation', 'Result', 'Detail'}
    if not required.issubset(rows.fieldnames or []):
        raise ValueError('Expected an English, comma-delimited Process Monitor export with Path, Operation, Result and Detail columns.')
    writes = 0
    byte_count = 0
    for row in rows:
        if (PureWindowsPath(row['Path']).name.lower() != 'nvlog.nvlgstg'
                or row['Operation'] != 'WriteFile' or row['Result'] != 'SUCCESS'):
            continue
        length = re.search(r'(?:^|,\s+)Length: ([0-9]+(?:,[0-9]{3})*)(?=,\s|$)', row['Detail'])
        if not length:
            raise ValueError(f'Unrecognized Length on CSV line {rows.line_num}; no total reported.')
        writes += 1
        byte_count += int(length[1].replace(',', ''))
    return writes, byte_count


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('capture', type=Path)
    args = parser.parse_args()
    try:
        with args.capture.open('rb') as probe:
            encoding = 'utf-16' if probe.read(2) in (b'\xff\xfe', b'\xfe\xff') else 'utf-8-sig'
        with args.capture.open(encoding=encoding, newline='') as capture:
            writes, byte_count = summarize(csv.DictReader(capture))
    except (OSError, ValueError, csv.Error) as error:
        parser.exit(1, f'{error}\n')
    print(f'{writes} successful writes; {byte_count:,} recorded bytes')
