#!/usr/bin/env python3
"""Compare the published Ome City workbooks and export inspectable source rows.

Usage: python3 compare-workbooks.py older.xlsx newer.xlsx ome-toilets.csv
Dependency: openpyxl.
"""
import argparse
from collections import Counter
import csv
import json
from pathlib import Path

from openpyxl import load_workbook

SHEET = '132055_public_toilet'
FIELDS = {
    'facility_id': 'ID',
    'name': '名称',
    'address': '所在地_連結表記',
    'location': '設置位置',
    'accessible_raw': 'バリアフリートイレ数',
    'wheelchair_raw': '車椅子使用者用トイレ有無',
    'infant_raw': '乳幼児用設備設置トイレ有無',
    'ostomate_raw': 'オストメイト設置トイレ有無',
    'opening_time': '利用開始時間',
    'closing_time': '利用終了時間',
    'schedule_note': '利用可能時間特記事項',
}


def load(path):
    workbook = load_workbook(path, read_only=True, data_only=True)
    try:
        source = iter(workbook[SHEET].values)
        header = next(source)
        id_index = header.index(FIELDS['facility_id'])
        records = {}
        for line, cells in enumerate(source, start=2):
            if not any(value is not None for value in cells):
                continue
            facility_id = cells[id_index]
            if not isinstance(facility_id, str) or not facility_id.strip() or facility_id in records:
                raise ValueError(f'{path}, row {line}: missing or duplicate facility ID')
            records[facility_id] = (line, cells)
        return header, records
    finally:
        workbook.close()


def classification(accessible, wheelchair):
    accessible_present = (isinstance(accessible, int) and accessible > 0) or accessible in (
        '有', '多目的トイレあり', '多機能トイレあり',
    )
    if accessible_present and wheelchair != '有':
        return 'accessible_only'
    if wheelchair == '有' and not accessible_present:
        return 'wheelchair_only'
    return 'other'


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('older', type=Path)
    parser.add_argument('newer', type=Path)
    parser.add_argument('csv', type=Path)
    args = parser.parse_args()
    older_header, older = load(args.older)
    header, newer = load(args.newer)
    if older_header != header:
        raise ValueError('Workbook columns differ. Align the schemas before comparing cells.')
    indexes = {key: header.index(field) for key, field in FIELDS.items()}
    common = older.keys() & newer.keys()
    outputs = []
    for row_number, cells in newer.values():
        record = {key: cells[index] for key, index in indexes.items()}
        record['source_row'] = row_number
        record['check'] = classification(record['accessible_raw'], record['wheelchair_raw'])
        outputs.append(record)
    with args.csv.open('w', encoding='utf-8-sig', newline='') as handle:
        writer = csv.DictWriter(handle, fieldnames=[*FIELDS, 'source_row', 'check'])
        writer.writeheader()
        writer.writerows(outputs)
    print(json.dumps({
        'columns_per_workbook': len(header),
        'older_rows': len(older),
        'newer_rows': len(newer),
        'shared_ids': len(common),
        'older_only': sorted(older.keys() - newer.keys()),
        'newer_only': sorted(newer.keys() - older.keys()),
        'changed_ids': sorted(key for key in common if older[key][1] != newer[key][1]),
        'accessible_raw': Counter(str(row['accessible_raw']) for row in outputs),
        'wheelchair_raw': Counter(str(row['wheelchair_raw']) for row in outputs),
        'checks': Counter(row['check'] for row in outputs),
    }, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()
