#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import random
import requests
import os

weather_api_site="https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={long}&timezone=auto&daily=weathercode,temperature_2m_max,temperature_2m_min,sunrise,sunset&forecast_days=1"

cityfile="geonames.csv"

weather_codes = {0:"sereno",
                 1:"prevalentemente sereno",
                 2:"parzialmente nuvoloso",
                 3:"nuvoloso",
                 45:"nebbioso",
                 48:"nebbioso",
                 51:"lieve pioggerella",
                 53:"moderata pioggerella",
                 55:"intensa pioggerella",
                 56:"lieve pioggerella",
                 57:"intensa pioggerella",
                 61:"lievi precipitazioni",
                 63:"moderate precipitazioni",
                 65:"intense precipitazioni",
                 66:"lievi precipitazioni",
                 67:"intense precipitazioni",
                 71:"lievi nevicate",
                 73:"moderate nevicate",
                 75:"intense nevicate",
                 77:"grandinate",
                 80:"lievi acquazzoni",
                 81:"moderati acquazzoni",
                 82:"violenti acquazzoni",
                 85:"lievi nevicate",
                 86:"intensei nevicate" ,
                 95:"temporali",
                 96:"temporali con lievi grandinate",
                 99:"temporali con forti grandinate"

                 }

def select_random_city():
    with open(cityfile) as csvfile:
        reader = csv.DictReader(csvfile)
        line = random.choice(list(reader))
    return line


def format_tts(city, country, weather_code, max_temperature, min_temperature): 
    weather_condition = weather_codes[weather_code]
    text_to_speech = f"""Oggi a {city}, {country} il meteo sarà {weather_condition}, 
    la temperatura minima sarà di {min_temperature} gradi e la massima di {max_temperature} gradi"""
    return text_to_speech


def get_audio_file(text_to_speech):
    print(text_to_speech)
#    os.system("espeak-ng '{tts}' -v mb-it1 -w random_weather_forecast.wav".format(tts=text_to_speech))     
    os.system("spd-say -l it-IT '{tts}'".format(tts=text_to_speech))     


def retrieve_forecast():
    city_dict = select_random_city() 
    try:
        api_string = weather_api_site.format(lat = city_dict['Latitude'], long = city_dict['Longitude'])
        city_forecast = requests.get(api_string).json()

    except Exception as e:
        print(e)
    daily_forecast = city_forecast['daily']
    tts = format_tts(
        city_dict['Name'], 
        city_dict['Country'],
        daily_forecast['weathercode'][0],
        daily_forecast['temperature_2m_max'][0],
        daily_forecast['temperature_2m_min'][0]
    )

    get_audio_file(tts)

retrieve_forecast()
