#!/usr/bin/env python

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


def encodeWikiLink(link: str) -> str:
    link = link.replace(' ', '_')
    parts = link.split('/')
    parts[-1] = quote(parts[-1])
    return '/'.join(parts)

def fetchCoordinates(link: str) -> list:
    link = encodeWikiLink(link)
    if link.startswith('//'):
        link = 'https:' + link
    try:
        process = Popen(["python", "wiki2geojson.py", f"{link}"], 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 {link}: {e}")
        pass
    return [0, 0]

try:
    with open(sys.argv[1], 'r') as fp:
        try:
            data = json.load(fp)
        except ValueError as e:
            print("Could not decode json: " + str(e))
            sys.exit(1)
except IOError as e:
    print("Could not decode json: " + str(e))
    sys.exit(1)

for entry in data:
    department = unquote(sys.argv[1].replace('.json', '').replace('_', ' '))
    x = re.search('.*href="(.*?)".*>(.*?)</a>', entry['Gemeinde'])
    muncipality = x.group(2)
    muncipalityLink = x.group(1)
    arrondissment = ''
    arrondissmentLink = ''
    postcode = []
    for key in entry:
        if key == 'PLZ' or "Post" in key:
            postcode = entry[key].split(' ')
        elif 'Arrondissement' in key:
            x = re.search('.*href="(.*?)".*>(.*?)</a>', entry[key])
            arrondissment = x.group(2)
            arrondissmentLink = x.group(1)
    insee = entry['Code INSEE']
    area = entry['Fl\u00e4che in km\u00b2'].replace('.', '').replace(',', '.')
    [lat, lon] = fetchCoordinates(muncipalityLink)

    newEntry = [
        muncipality,
        muncipalityLink,
        arrondissment,
        arrondissmentLink,
        department,
        postcode,
        insee,
        area,
        lat,
        lon
    ]
    print(newEntry)