import os
import requests
import requests.exceptions
import json

repos = open("places.json")
repoData = json.load(repos)

alreadyRetrieved = []

def isRetrieved(place):
    return place in alreadyRetrieved


for index, place in enumerate(repoData['places']):
    print(">----------<")

    if (place is None):
        print(
            f"Failed to get weather at {str(index)} because insufficient data was supplied.")
        continue

    if (isRetrieved(place)):
        print(
            f'Skipped fetching weather for {place} as it was already fetched.')
        continue

    print(f"Fetching weather: {place}")
    try:
        res = requests.get(f"https://wttr.in/{place}?format=j1", headers={"Accept": "application/json"})
        res.raise_for_status()
        
        responseData = json.loads(str("{\"weather\": " + res.text + "}"))
        
        file = open(
            f"weather/{place}.json", "w")
        file.write(json.dumps(responseData, indent=2, sort_keys=True))
        file.close()

        alreadyRetrieved.append(place)

        print(f"Weather for {place} was found!")
    except requests.exceptions.HTTPError:
        print(f'Failed to find place {place}')
    except Exception as e:
        print(f"Failed to find weather for {place}")
        print("Reason:", end=" ")
        print(e)

print(">----------<")

print('Cleaning Up...')


def noLongerRequired(place):
    if (place not in repoData['places']):
        os.remove(f"./weather/{place}.json")
        print(f'{place} was removed!')


for place in os.listdir('weather'):
  if (not place.endswith('.txt')):
      noLongerRequired(os.path.splitext(place)[0])

import os
import requests
import requests.exceptions
import json

repos = open("places.json")
repoData = json.load(repos)

alreadyRetrieved = []

def isRetrieved(place):
    return place in alreadyRetrieved


for index, place in enumerate(repoData['places']):
    print(">----------<")

    if (place is None):
        print(
            f"Failed to get weather at {str(index)} because insufficient data was supplied.")
        continue

    if (isRetrieved(place)):
        print(
            f'Skipped fetching weather for {place} as it was already fetched.')
        continue

    print(f"Fetching weather: {place}")
    try:
        res = requests.get(f"https://wttr.in/{place}?format=j1", headers={"Accept": "application/json"})
        res.raise_for_status()
        
        responseData = json.loads(str("{\"weather\": " + res.text + "}"))
        
        file = open(
            f"weather/{place}.json", "w")
        file.write(json.dumps(responseData, indent=2, sort_keys=True))
        file.close()

        alreadyRetrieved.append(place)

        print(f"Weather for {place} was found!")
    except requests.exceptions.HTTPError:
        print(f'Failed to find place {place}')
    except Exception as e:
        print(f"Failed to find weather for {place}")
        print("Reason:", end=" ")
        print(e)

print(">----------<")

print('Cleaning Up...')


def noLongerRequired(place):
    if (place not in repoData['places']):
        os.remove(f"./weather/{place}.json")
        print(f'{place} was removed!')


for place in os.listdir('weather'):
  if (not place.endswith('.txt')):
      noLongerRequired(os.path.splitext(place)[0])
