"""Export Dublin cycle parking CSV to GeoJSON with DuckDB's GDAL integration."""

import argparse
from pathlib import Path

import duckdb


def main():
    options = argparse.ArgumentParser(description=__doc__)
    options.add_argument('source', type=Path)
    options.add_argument('output', type=Path)
    options.add_argument('--exclude-coordinate-columns', action='store_true')
    options.add_argument('--extension-directory', type=Path)
    args = options.parse_args()
    if args.output.exists():
        raise SystemExit(f'Choose a new output path. {args.output} already exists.')
    driver_options = [
        'X_POSSIBLE_NAMES=Longitude',
        'Y_POSSIBLE_NAMES=Latitude',
        'KEEP_GEOM_COLUMNS=NO' if args.exclude_coordinate_columns else 'KEEP_GEOM_COLUMNS=YES',
    ]
    config = {'extension_directory': str(args.extension_directory.resolve())} if args.extension_directory else {}
    with duckdb.connect(config=config) as connection:
        connection.execute('LOAD spatial')
        connection.execute('SET geometry_always_xy = true')
        connection.execute('''
            CREATE TEMP TABLE source AS
            SELECT * EXCLUDE (OGC_FID)
            FROM ST_Read(?, allowed_drivers=['CSV'], open_options=?)
        ''', [str(args.source.resolve()), driver_options])
        connection.execute('''
            COPY source TO ? WITH (
                FORMAT GDAL, DRIVER 'GeoJSON', GEOMETRY_TYPE 'POINT',
                LAYER_CREATION_OPTIONS ('RFC7946=YES', 'COORDINATE_PRECISION=9'),
                SRS 'EPSG:4326'
            )
        ''', [str(args.output.resolve())])


if __name__ == '__main__':
    main()
