import csv


def write_page_report(out_path, history):
    """
    Write out page report from given path and data.

    Rows which contain duplicate URLs will be skipped. The data is expected to
    be sorted already so duplicates are removed by comparing consecutive rows.

    :param out_path: Path of CSV to write page report to.
    :param history: History data to use.

    :return: Count of rows written out.
    """
    header = (
        'year_month',
        'timestamp',
        'domain',
        'path',
        'query',
        'fragment',
        'title',
        'full_url',
    )

    with open(out_path, 'w') as f_out:
        writer = csv.DictWriter(f_out, fieldnames=header)
        writer.writeheader()

        wrote_count = 0
        # Skip rows which contain a duplicate of the previous row's URL.
        # We've sorted by URL and then timestamp
        previous_row = None
        for row in history:
            if previous_row is None or row['full_url'] != previous_row['full_url']:
                writer.writerow(row)
                wrote_count += 1
            previous_row = row

    return wrote_count