#!/usr/bin/env python3
"""Compare Iida's recycling CSV and Excel export, and extract finder fields."""

import argparse
import csv
from pathlib import Path

from openpyxl import load_workbook


FIELDS = {
    "station_id": "ゴミ集積場所_ID",
    "name": "ゴミ集積場所_名称",
    "kana": "ゴミ集積場所_名称（カナ）",
    "district": "ゴミ集積場所_地区名",
    "source_schedule": "ゴミ集積場所_ゴミ収集日",
}


def compare(csv_path, workbook_path, output):
    with csv_path.open(encoding="utf-8-sig", newline="") as source:
        csv_rows = list(csv.reader(source))
    workbook = load_workbook(workbook_path, read_only=True, data_only=True)
    try:
        excel_rows = [
            ["" if cell is None else str(cell) for cell in row]
            for row in workbook.active.values
        ]
    finally:
        workbook.close()

    if not csv_rows or len(csv_rows) != len(excel_rows):
        raise ValueError("CSV and Excel row counts differ")
    for number, (csv_row, excel_row) in enumerate(zip(csv_rows, excel_rows), 1):
        if csv_row != excel_row:
            raise ValueError(f"CSV and Excel differ on source row {number}")

    headers, *rows = csv_rows
    positions = {key: headers.index(label) for key, label in FIELDS.items()}
    station_ids = [row[positions["station_id"]] for row in rows]
    if not all(station_ids) or len(set(station_ids)) != len(station_ids):
        raise ValueError("missing or duplicate station IDs")

    with output.open("w", encoding="utf-8-sig", newline="") as result:
        writer = csv.writer(result, lineterminator="\n")
        writer.writerow([*FIELDS, "source_row"])
        for number, row in enumerate(rows, 2):
            writer.writerow([*(row[index] for index in positions.values()), number])
    print(f"{len(rows)} station records, {len(headers)} columns, all fields matched")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source_csv", type=Path)
    parser.add_argument("source_xlsx", type=Path)
    parser.add_argument("output_csv", type=Path)
    args = parser.parse_args()
    compare(args.source_csv, args.source_xlsx, args.output_csv)
