"""Convert reviewed flat string records; no automatic repair.
Place json-syntax-gate.py beside this file.
python reviewed-json-to-csv.py reviewed.json new-output.csv
"""
import csv, importlib.util, sys
from pathlib import Path
sys.dont_write_bytecode = True

def export(source, target):
    module_path = Path(__file__).with_name('json-syntax-gate.py')
    spec = importlib.util.spec_from_file_location('syntax_gate', module_path)
    gate = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(gate)
    report, rows = gate.check(source)
    if not report['accepted']:
        raise ValueError(report['error'])
    fields = ['id', 'url', 'note']
    if not isinstance(rows, list) or not rows:
        raise ValueError('a nonempty array is required')
    for row in rows:
        if not isinstance(row, dict) or set(row) != set(fields):
            raise ValueError('each row must contain only id, url and note')
        if not all(type(row[key]) is str for key in fields):
            raise ValueError('every field must be a JSON string')
    with Path(target).open('x', encoding='utf-8', newline='') as file:
        writer = csv.DictWriter(file, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)

if __name__ == '__main__':
    export(sys.argv[1], sys.argv[2])
