#!/usr/bin/env python3
import csv
import sys
from pathlib import Path
from typing import List

def load_rows(path: Path, encoding="utf-8-sig"):
    with path.open("r", encoding=encoding, newline="") as f:
        rdr = csv.reader(f)
        try:
            header = next(rdr)
        except StopIteration:
            return [], []
        rows = [row for row in rdr]
    return header, rows

def write_rows(path: Path, header: List[str], rows: List[List[str]], encoding="utf-8"):
    with path.open("w", encoding=encoding, newline="") as f:
        w = csv.writer(f)
        if header:
            w.writerow(header)
        for r in rows:
            w.writerow(r)

def first_of_triplets(input_csv: Path, output_csv: Path):
    header, rows = load_rows(input_csv)
    out = []

    i = 0
    n = len(rows)
    while i < n:
        # Need at least 3 rows remaining to check a triplet
        if i + 2 < n:
            c0  = rows[i][0]  if len(rows[i])   > 0 else ""
            c1  = rows[i+1][0] if len(rows[i+1]) > 0 else ""
            c2  = rows[i+2][0] if len(rows[i+2]) > 0 else ""
            if c0 == c1 == c2:
                # Found a triplet or longer run. Emit only the first row.
                out.append(rows[i])

                # Skip the entire run of identical first-column values (robust to 3+)
                val = c0
                j = i + 3
                while j < n and (rows[j][0] if len(rows[j]) > 0 else "") == val:
                    j += 1
                i = j
                continue

        # No triplet starting at i -> advance
        i += 1

    write_rows(output_csv, header, out)

def main(argv: list):
    if len(argv) < 3:
        print("Usage: pick_first_of_triplets.py <input.csv> <output.csv>")
        print("Behavior:")
        print("  - Assumes the CSV is pre-sorted so duplicates are adjacent.")
        print("  - Looks only at the FIRST COLUMN to detect triplets.")
        print("  - When it sees three or more consecutive rows with the SAME first-column value,")
        print("    it writes ONLY the first row from that run and skips the rest.")
        print("  - All other rows (not beginning a triplet) are ignored.")
        sys.exit(1)
    inp = Path(argv[1])
    out = Path(argv[2])
    first_of_triplets(inp, out)

if __name__ == "__main__":
    main(sys.argv)
