#!/usr/bin/env python3
# dedup_adjacent_by_firstcol.py
#
# Usage:
#   python3 dedup_adjacent_by_firstcol.py input.csv output.csv --header
#
#   python3 noDupFullRow.py sourceNames_dups.csv sourceNames.csv
#
# Drops adjacent duplicate rows where the first column equals the previous row's
# first column (string match after .strip()). Keeps all columns for kept rows.
# If --header is provided, the first row is copied through unmodified and not
# used for duplicate comparison.

import sys
import csv
from pathlib import Path

def main():
    if len(sys.argv) < 3:
        print("Usage: python3 dedup_adjacent_by_firstcol.py INPUT.csv OUTPUT.csv [--header]")
        sys.exit(1)

    in_path = Path(sys.argv[1])
    out_path = Path(sys.argv[2])
    has_header = len(sys.argv) >= 4 and sys.argv[3] == "--header"

    if not in_path.exists():
        print(f"Input not found: {in_path}")
        sys.exit(1)

    with in_path.open(newline="", encoding="utf-8") as fin, \
         out_path.open("w", newline="", encoding="utf-8") as fout:
        reader = csv.reader(fin)
        writer = csv.writer(fout, lineterminator="\n")

        prev_first = None

        if has_header:
            try:
                header = next(reader)
            except StopIteration:
                return
            writer.writerow(header)
            prev_first = None  # don't compare header to first data row

        for row in reader:
            if not row:
                continue  # skip empty rows
            first = row[0].strip()
            if first != (prev_first if prev_first is not None else object()):
                writer.writerow(row)
                prev_first = first
            # else: skip row (adjacent duplicate by first column)

if __name__ == "__main__":
    main()
