import csv
import sys
from pathlib import Path


def read_rows(path):
    """Read every row of a CSV into a list of lists."""
    with open(path, newline="", encoding="utf-8") as f:
        return list(csv.reader(f))


def clean_rows(rows):
    """Trim whitespace from each field and drop fully-empty rows."""
    cleaned = []
    for row in rows:
        trimmed = [field.strip() for field in row]
        if any(trimmed):
            cleaned.append(trimmed)
    return cleaned


def write_rows(rows, path):
    with open(path, "w", newline="", encoding="utf-8") as f:
        csv.writer(f).writerows(rows)


def main():
    if len(sys.argv) < 2:
        print("Usage: python csv_cleaner.py <input.csv> [output.csv]")
        raise SystemExit(1)

    in_path = Path(sys.argv[1])
    if len(sys.argv) > 2:
        out_path = Path(sys.argv[2])
    else:
        out_path = in_path.with_name(in_path.stem + ".clean.csv")

    try:
        rows = read_rows(in_path)
    except FileNotFoundError:
        print(f"No such file: {in_path}")
        raise SystemExit(1)

    cleaned = clean_rows(rows)
    write_rows(cleaned, out_path)
    print(f"Read {len(rows)} rows, wrote {len(cleaned)} clean rows to {out_path}")


if __name__ == "__main__":
    main()
