import csv, json, sys
from pathlib import Path

def reject_constant(token):
    raise ValueError("Non-JSON constant: " + token)

def unique_keys(pairs):
    out = {}
    for key, value in pairs:
        if key in out:
            raise ValueError("Duplicate key: " + key)
        out[key] = value
    return out

def export(source, target):
    source, target = Path(source), Path(target)
    if source.resolve() == target.resolve():
        raise ValueError("Source and destination must differ")
    if source.stat().st_size > 1_000_000:
        raise ValueError("Demo input cap exceeded")
    data = json.loads(source.read_text(encoding="utf-8"),
        parse_constant=reject_constant, object_pairs_hook=unique_keys)
    if not isinstance(data, list):
        raise ValueError("Expected an array")
    for row in data:
        if not isinstance(row, dict) or set(row) != {"id", "text"}:
            raise ValueError("Expected exact id/text objects")
        if not all(isinstance(row[k], str) for k in ("id", "text")):
            raise ValueError("id and text must be strings")
    with target.open("x", encoding="utf-8", newline="") as f:
        w = csv.writer(f, lineterminator="\n")
        w.writerow(["id", "text"])
        w.writerows((r["id"], r["text"]) for r in data)

if __name__ == "__main__":
    try:
        export(sys.argv[1], sys.argv[2])
    except (ValueError, OSError) as e:
        print(str(e), file=sys.stderr)
        sys.exit(1)
