#! /usr/bin/env python3

import sys, json
from urllib.parse import quote
from subprocess import Popen, PIPE


def getWikiUrlFromLine(line):
    entry = line.split(',')
    wikiurl = entry[1].strip()[1:-1] # Remove the surrounding quotes
    parts = wikiurl.split('/')
    parts[-1] = quote(parts[-1])
    return '/'.join(parts)

def fetchCoordinates(wikiurl):
    try:
        process = Popen(["python", "wiki2geojson.py", f"https:{wikiurl}"], stdout=PIPE)
        (output, err) = process.communicate()
        exit_code = process.wait()
        if exit_code == 0:
            geojson = json.loads(output)
            return [
                geojson['features'][0]['geometry']['coordinates'][1],
                geojson['features'][0]['geometry']['coordinates'][0]
            ]
    except Exception as e:
        print(f"Error fetching coordinates for {wikiurl}: {e}")
    return [0, 0]

# Main program:
try:
    with open(sys.argv[1], 'r', encoding='utf-8') as fp:
        while True:
            line = fp.readline()
            if not line:
                break
            line = line.strip()
            wikiurl = getWikiUrlFromLine(line)
            lon, lat = fetchCoordinates(wikiurl)
            print(line.replace(', 0, 0]', f', {lat}, {lon}]'))
except IOError as e:
    print("Could not decode json: " + str(e))
    sys.exit(1)
