import click
import re
import gpxpy

coords_pattern = re.compile(r'predict:\s+(?P<state>\S+)?\s*velocity=(?P<velocity>[\d+\.?]+)\s+pos=\[\[-?(?P<lat>\d+\.\d+), -?(?P<lon>\d+\.\d+)\]\]')

@click.command
@click.argument('input', type=click.File('r'))
def main(input):
    gpx = gpxpy.gpx.GPX()
    track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(track)
    segment = gpxpy.gpx.GPXTrackSegment()
    track.segments.append(segment)

    for line in map(lambda x: x[:-1], input.readlines()):
        props = coords_pattern.search(line)
        if props is not None:
            named_props = props.groupdict()
            coords = gpxpy.gpx.GPXTrackPoint(float(named_props['lat']), float(named_props['lon']), elevation=named_props['velocity'])
            if 'state' in named_props:
                coords.comment = named_props['state']
            segment.points.append(coords)

    print(gpx.to_xml())

if __name__ == "__main__":
    main()
