"""Compare a Dublinked cycle-parking download against its CKAN DataStore."""

import argparse
import csv
import hashlib
import json
from collections import Counter
from decimal import Decimal
from pathlib import Path

RESOURCE_ID = '0777c3a7-19ed-4e5b-a498-fd891334dbcf'
TEXT_FIELDS = ('type_stands', 'location_stand', 'no_stands')
COORDINATE_FIELDS = ('Latitude', 'Longitude', 'Easting', 'Northing')
FIELDS = (*TEXT_FIELDS, *COORDINATE_FIELDS)
LOCATIONS = ('Drury Street Car Park', 'Jervis Street Car Park')


def signature(record):
    values = [record[field] if record[field] is not None else '' for field in TEXT_FIELDS]
    for field in COORDINATE_FIELDS:
        value = record[field]
        values.append(None if value in (None, '') else Decimal(str(value)))
    return tuple(values)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('source', type=Path)
    parser.add_argument('datastore', type=Path)
    args = parser.parse_args()

    with args.source.open(encoding='utf-8-sig', newline='') as stream:
        reader = csv.DictReader(stream)
        if tuple(reader.fieldnames or ()) != FIELDS:
            raise SystemExit('The CSV headers do not match the seven source fields.')
        source = [signature(row) for row in reader]

    result = json.loads(args.datastore.read_text(), parse_float=Decimal)
    if not result['success']:
        raise SystemExit('CKAN reported an unsuccessful request.')
    data = result['result']
    if data['resource_id'] != RESOURCE_ID:
        raise SystemExit('The DataStore reply belongs to a different resource.')
    if data.get('total_was_estimated') or len(data['records']) != data.get('total'):
        raise SystemExit('Retrieve the complete set of DataStore records and the exact total.')
    records = sorted(data['records'], key=lambda row: row['_id'])
    api = [signature(row) for row in records]
    source_counts = Counter(source)
    api_counts = Counter(api)
    missing = sum((source_counts - api_counts).values())
    extra = sum((api_counts - source_counts).values())
    pairs = {
        location: [
            {'apiId': row['_id'], 'type': row['type_stands']}
            for row in records if row['location_stand'] == location
        ]
        for location in LOCATIONS
    }
    print(json.dumps({
        'sourceHash': hashlib.sha256(args.source.read_bytes()).hexdigest(),
        'officialResourceId': data['resource_id'],
        'csvRows': len(source),
        'apiRows': len(api),
        'comparedFields': FIELDS,
        'sameOrderByApiId': source == api,
        'missing': missing,
        'extra': extra,
        'recordsToInspect': pairs,
    }, indent=2))
    return int(source != api)


if __name__ == '__main__':
    raise SystemExit(main())
