#!/usr/bin/env python3
"""Simplify the list of contributors of markdownlint, 2/2"""

# name:    simpler_list.py
# author:  nbehrnd@yahoo.com
# license: MIT
# date:    [2022-12-12 Mon]
# edit:    [2023-01-21 Sat]

# Why:
# The list of the contributors extracted by bash script `git_report.sh` already
# is a chronological sort, though authors with merged contributions in multiple
# years appear multiple times.  This script processes the intermediate record,
# and retains only the first date of contribution by check of the email address.

# This is the second of two assistant scripts written.
#
# How:
# Copy-paste this script into a local git repository of `markdownlint`.  Run
# script `git_report.sh` (see there) for an intermediate list.  Then call
#
# ```shell
# python3 ./simpler_list.py [listing.txt]
# ```
#
# to process the intermediate listing file written by `git_report.sh`.  The
# newly written file `shortlist.txt` is the permanent record of content to add
# to file `copyright`.
#
# Written for and tested with Python 3.10.9 as provided by Debian 12/bookworm --
# only modules of the standard library are used.

import argparse
import sys


def collect_parameters():
    """initialize where to work"""
    parser = argparse.ArgumentParser(
        description="Simplify the list of contributors of `markdownlint`")
    parser.add_argument(
        "file", help="Input file (which is generated by git_report.sh)")
    args = parser.parse_args()

    return args.file


def reader():
    """read the intermediate listing"""
    contact_register = []
    output_list = []

    input_file = collect_parameters()
    try:
        with open(input_file, mode="r", encoding="utf-8") as source:
            for line in source:
                email = ""
                email = str(line).strip().split()[-1]
                if email not in contact_register:
                    contact_register.append(email)
                    output_list.append(str(line).strip())
    except IOError:
        print(f"File '{input_file}' is not accessible.  Exit.")
        sys.exit()

    return output_list


def writer():
    """(over)write a new permanent record"""
    output_file = "shortlist.txt"
    output_list = reader()

    try:
        with open(output_file, mode="w", encoding="utf-8") as newfile:
            for entry in output_list:
                newfile.write(f"{entry}\n")
    except IOError:
        print(f"File {output_file} can not be written.  Exit.")
        sys.exit()


def main():
    """join the functionalities"""
    collect_parameters()
    writer()


if __name__ == "__main__":
    main()
