"""Export original amount number tokens from a small flat JSON array.
python decimal-tokens-to-csv.py decimal-token-example.json new-output.csv
"""
import csv, json, sys
from pathlib import Path

class NumberToken(str):
    pass

def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('duplicate key: ' + repr(key))
        result[key] = value
    return result

def reject_constant(value):
    raise ValueError('non-JSON number: ' + value)

def export(source, target):
    source, target = Path(source), Path(target)
    if source.stat().st_size > 2_000_000:
        raise ValueError('this small example caps input at 2,000,000 bytes')
    if target.exists():
        raise FileExistsError('choose a new output filename')
    records = json.loads(source.read_text(encoding='utf-8'),
        parse_float=NumberToken, parse_int=NumberToken,
        parse_constant=reject_constant, object_pairs_hook=unique_object)
    if not isinstance(records, list) or not records:
        raise ValueError('a nonempty array is required')
    for record in records:
        if not isinstance(record, dict) or set(record) != {'id', 'amount'}:
            raise ValueError('each record must contain only id and amount')
        if type(record['id']) is not str:
            raise ValueError('id must be a JSON string')
        if not isinstance(record['amount'], NumberToken):
            raise ValueError('amount must be a JSON number, not a quoted string')
    with target.open('x', encoding='utf-8', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['id', 'amount_token'])
        writer.writerows((record['id'], record['amount']) for record in records)

if __name__ == '__main__':
    export(sys.argv[1], sys.argv[2])
